importjava.io.IOException;
importjava.sql.*;
importjava.util.List;
importjava.util.Properties;
publicclasstool{
toolk=newtool();
privatestaticStringurl=null;
privatestaticStringusername=null;
privatestaticStringpassword=null;
privatestaticPropertiesprops=newProperties();
static{
try{
props.load(tool.class.getResourceAsStream("/jdbc.properties"));
}catch(IOExceptione){
e.printStackTrace();
System.out.println("加载properties文件异常");
}
url=(props.getProperty("jdbc.url"));
username=(props.getProperty("jdbc.username"));
password=(props.getProperty("jdbc.password"));
//注册驱动类
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundExceptione){
e.printStackTrace();
System.out.println("加载驱动异常");
}
}
/**
*创建一个数据库连接
*
*@return一个数据库连接
*/
publicstaticConnectiongetConnection(){
Connectionconn=null;
//创建数据库连接
try{
conn=DriverManager.getConnection(url,username,password);
}catch(SQLExceptione){
e.printStackTrace();
System.out.println("数据库连接出错");
}
returnconn;
}
publicstaticResultSetexecuteQuery(Connectionconn,StringstaticSql){
ResultSetrs=null;
try{
//创建执行SQL的对象
Statementstmt=conn.createStatement();
//执行SQL,并获取返回结果
rs=stmt.executeQuery(staticSql);
}catch(SQLExceptione){
e.printStackTrace();
}
returnrs;
}
publicstaticvoidexecuteSQL(Connectionconn,StringstaticSql){
try{
//创建执行SQL的对象
Statementstmt=conn.createStatement();
//执行SQL,并获取返回结果
stmt.execute(staticSql);
}catch(SQLExceptione){
e.printStackTrace();
System.out.println("执行SQL语句出错");
}
}
publicstaticvoidexecuteBatchSQL(Connectionconn,ListsqlList){
try{
//创建执行SQL的对象
Statementstmt=conn.createStatement();
for(Stringsql:sqlList){
stmt.addBatch(sql);
}
//执行SQL,并获取返回结果
stmt.executeBatch();
}catch(SQLExceptione){
e.printStackTrace();
System.out.println("");
}
}
publicstaticvoidcloseConnection(Connectionconn){
if(conn==null)return;
try{
if(!conn.isClosed()){
//关闭数据库连接
conn.close();
}
}catch(SQLExceptione){
e.printStackTrace();
System.out.println("关闭数据库异常");
}
}
publicvoidclose(Connectionconnection){
//TODOAuto-generatedmethodstub
}
}