package jing.lian.kui.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import jing.lian.kui.common.Common;
public class DBUtil {
private static Connection con = null;
private Statement statement;
private ResultSet resultSet;
private static String userName;
private static String password;
private static String driver;
private static String host;
private static String databasename;
private static String url;
private static String port;
private static Properties properties = null;
private final static String pathName = Common.decode(DBUtil.class.getResource("/config.properties").getPath());
static{
if(properties == null)
properties = new Properties();
try {
InputStream inputStream = new FileInputStream(pathName);
properties.load(inputStream);
inputStream.close();
init();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public DBUtil() {
}
public static void init(){
databasename = properties.getProperty("databasename");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
host = properties.getProperty("host");
port = properties.getProperty("port");
url =properties.getProperty("url")+host+":"+port+"/"+databasename;
}
public synchronized static Connection getConnection(){
if(con==null){
try {
System.out.println(driver);
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
e.printStackTrace();
}
}
return con;
}
public int update(String sql){
int i = 0;
con = getConnection();
try {
this.statement = con.createStatement();
i = statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
i = -1;
}finally{
this.close();
}
return i;
}
public ResultSet queryDate(String sql) {
con = getConnection();
try {
this.statement = con.createStatement();
this.resultSet = statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally{
this.close();
}
return this.resultSet;
}
/**
* 释放数据库资源
*/
public void close() {
try {
if (resultSet != null) {
resultSet.close();
resultSet = null;
}
if (statement != null) {
statement.close();
statement = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
properties文件:放在class文件下
userName = root
password = 000000
driver = com.mysql.jdbc.Driver
databasename = test
host = 127.0.0.1
port = 3306
url = jdbc:mysql://