由于建立connection会花费较长时间,
所以一直没有释放connection,
故该类只适合单线程,多线程使用可以改为线程池.
import com.sun.rowset.CachedRowSetImpl;
import java.sql.*;
public class DBHelper {
static String driver = "com.mysql.cj.jdbc.Driver";
static String url = "jdbc:mysql://localhost:3306/***(数据库名)?serverTimezone=GMT%2B8";
static String user = "root";
static String password = "123456";
public static Connection con;//建立连接消耗时间比较多,每次都重新建立连接的话会浪费很多时间,所以用作静态field
static {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
}catch (Exception e)
{
e.printStackTrace();
}
}
/*public static Connection getConnection()
{
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/communitymanagement?serverTimezone=GMT%2B8";
String user = "root";
String password = "mysql";
Connection con;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
return con;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}*/
//执行查询语句
public static ResultSet executeInquire(String sql, Object[] parameters)
{
try
{
//long t1=System.currentTimeMillis();
//Connection con=getConnection();//用时很长,933ms
//System.out.println(System.currentTimeMillis()-t1);
PreparedStatement pstm=con.prepareStatement(sql);
for (int i = 0; i <parameters.length ; i++) {
pstm.setObject(i+1,parameters[i]);
}
ResultSet rs=pstm.executeQuery();
CachedRowSetImpl crs=new CachedRowSetImpl();
crs.populate(rs);
rs.close();
pstm.close();
return crs;
}catch (Exception e){e.printStackTrace();return null;}
}
//不带参数的查询语句
public static ResultSet executeNoneInquire(String sql)
{
try
{
PreparedStatement pstm=con.prepareStatement(sql);
ResultSet rs= pstm.executeQuery();
CachedRowSetImpl crs=new CachedRowSetImpl();
crs.populate(rs);
rs.close();
pstm.close();
return crs;
}catch (Exception e){e.printStackTrace();return null;}
}
//执行更新语句
public static int excuteUpdate(String sql, Object[] parameters)
{
try
{
PreparedStatement pstm=con.prepareStatement(sql);
for (int i = 0; i <parameters.length ; i++) {
pstm.setObject(i+1,parameters[i]);
}
int rs= pstm.executeUpdate();
pstm.close();
return rs;
}catch (Exception e){e.printStackTrace();return 0;}
}
//执行存储过程
public static boolean excuteProcedure(String sql, Object[] parameters)
{
try
{
CallableStatement c=con.prepareCall(sql);
for (int i = 0; i <parameters.length ; i++) {
c.setObject(i+1,parameters[i]);
}
boolean y= c.execute();
c.close();
return y;
}catch (Exception e){e.printStackTrace();return false;}
}
}