改写为连接SQl server数据库:package lemon.util; import com.mysql.cj.jdbc.MysqlDataSource; import lemon.exception.SystemException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=book"; private static final String USERNAME = "sa"; private static final String PASSWORD = "123456"; private static volatile DataSource DATA_SOURCE; private DBUtil(){} private static DataSource getDataSource(){ if(DATA_SOURCE == null){ synchronized (DBUtil.class){ if(DATA_SOURCE == null){ DATA_SOURCE = new MysqlDataSource(); ((MysqlDataSource) DATA_SOURCE).setURL(URL); ((MysqlDataSource) DATA_SOURCE).setUser(USERNAME); ((MysqlDataSource) DATA_SOURCE).setPassword(PASSWORD); } } } return DATA_SOURCE; } public static Connection getConnection(){ try { return getDataSource().getConnection(); } catch (SQLException e) { throw new SystemException("000001", "获取数据库连接失败", e); } } public static void close(Connection c, Statement s){ close(c, s, null); } public static void close(Connection c, Statement s, ResultSet r){ try { if(r != null) r.close(); if(s != null) s.close(); if(c != null) c.close(); } catch (SQLException e) { throw new SystemException("000002", "释放数据库资源出错", e); } } }
时间: 2024-02-14 20:12:47 浏览: 75
package lemon.util;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import lemon.exception.SystemException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=book";
private static final String USERNAME = "sa";
private static final String PASSWORD = "123456";
private static volatile DataSource DATA_SOURCE;
private DBUtil(){}
private static DataSource getDataSource(){
if(DATA_SOURCE == null){
synchronized (DBUtil.class){
if(DATA_SOURCE == null){
DATA_SOURCE = new SQLServerDataSource();
((SQLServerDataSource) DATA_SOURCE).setURL(URL);
((SQLServerDataSource) DATA_SOURCE).setUser(USERNAME);
((SQLServerDataSource) DATA_SOURCE).setPassword(PASSWORD);
}
}
}
return DATA_SOURCE;
}
public static Connection getConnection(){
try {
return getDataSource().getConnection();
} catch (SQLException e) {
throw new SystemException("000001", "获取数据库连接失败", e);
}
}
public static void close(Connection c, Statement s){
close(c, s, null);
}
public static void close(Connection c, Statement s, ResultSet r){
try {
if(r != null)
r.close();
if(s != null)
s.close();
if(c != null)
c.close();
} catch (SQLException e) {
throw new SystemException("000002", "释放数据库资源出错", e);
}
}
}
阅读全文