package com.zyna.db;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.applet.Main;
/**
*
* @author Administrator
*/
public class DbAccessor {
private Connection conn;
private Statement stmt;
//boco server posgresql
private String hostIp="10.0.3.40";
//local
//private String hostIp="localhost";
private String port="5432";
private String dbName="smp_main";
//server
private String dbAdmin="smp";
//private String dbAdmin="postgres";
//
//boco server posgresql
private String dbPassword="smpboco";
//local
// private String dbPassword="orcl";
// Class.forName("org.postgresql.Driver").newInstance();
// String url ="jdbc:postgresql://localhost/myDB"
// //myDB为数据库名
// String user="myuser";
// String password="mypassword";
// Connection conn= DriverManager.getConnection(url,user,password);
// 请给我个完整的代码,我在数据库里建了一个库叫harddisk,
//
private void getConnection() {
try {
// TODO code application logic here
//加载驱动
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("org.postgresql.Driver");
try {
//连接数据库
// conn = DriverManager.getConnection("jdbc:sqlserver://" + hostIp + ":"
// + port + ";databaseName=" + dbName, dbAdmin, dbPassword);
String str = "jdbc:postgresql://" + hostIp + ":"+ port + ";databaseName=" + dbName;
System.out.println("str-->"+str);
conn = DriverManager.getConnection("jdbc:postgresql://" + hostIp + ":"+ port + "/" + dbName, dbAdmin, dbPassword);
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("数据库连接失败!!");
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("数据库驱动程序加载失败!");
}
}
public ResultSet execute(String sql){
try{
if(conn==null){
getConnection();
}
//创建Statement对象
stmt = conn.createStatement();
try {
//将SQL字符串送给Statement执行
ResultSet rs;
//如果SQL语句是SELECT语句
if(sql.substring(0, 6).equalsIgnoreCase("select")){
rs= stmt.executeQuery(sql);
return rs;
} else{
stmt.executeUpdate(sql);
return null;
}
} catch (SQLException ex) {
System.out.println("SQL语句执行错误!!!");
System.out.println(sql);
}
} catch (SQLException ex) {
System.out.println("创建Statement失败!!");
}
return null;
}
public void close() {
try {
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DbAccessor.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args){
DbAccessor dbAccessor = new DbAccessor();
dbAccessor.getConnection();
}
}
连接数据库postgresql
最新推荐文章于 2019-03-05 10:10:27 发布