转:JDBC连接MYSQL数据库 单例模式

时间:2022-09-22 00:01:54
public class SqlHelper
{
private final Lock lock = new ReentrantLock();
private static final SqlHelper sqlHelper = new SqlHelper();
/**
* 私有的默认构造方法
*/
private SqlHelper()
{
}
/**
* 静态方法获得单例
*/
public static SqlHelper getInstance()
{
return sqlHelper;
}
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PWD = "root";
private Connection conn = null;
public Connection getConnection()
{
try
{
Class.forName(DRIVER);
return DriverManager.getConnection(URL, USER, PWD);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
public ResultSet executeQuery(String sql, Object[] params)
{
try
{
this.conn = this.getConnection();
PreparedStatement pst
= conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++)
{
pst.setObject(i
+ 1, params[i]);
}
return pst.executeQuery();
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
public void closeConnection()
{
try
{
if (this.conn != null && !conn.isClosed())
{
conn.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql)
{
try
{
this.conn = this.getConnection();
PreparedStatement pst
= conn.prepareStatement(sql);
return pst.executeQuery();
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
public int executeUpdate(String sql, Object[] params)
{
this.lock.lock();
PreparedStatement pst
= null;
int num = 0;
try
{
this.conn = this.getConnection();
pst
= conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++)
{
pst.setObject(i
+ 1, params[i]);
}
num
= pst.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
this.closeConnection();
this.lock.unlock();
}
return num;
}
}