JDBC连接数据库(Sql Server 2008)

时间:2022-06-02 19:42:01

JDBC连接Sql Server 2008:

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {

private static Properties properties;// 用于读取配置文件对象;
static {
properties = new Properties();
try (InputStream is = JDBCUtils.class
.getResourceAsStream("/CdcIfsDb.properties");) {// 获取输入流
properties.load(is);// 加载
} catch (IOException e) {
e.printStackTrace();
}
}

//获得数据库连接;
public static Connection getConnection() {
Connection conn = null;
String sql = null;
ResultSet rs = null;
PreparedStatement pst = null;
String DBDRIVER = properties.getProperty("driver");
String DBURL = properties.getProperty("DBURL");
String DBUSER = properties.getProperty("DBUSER");
String DBPASSWORD = properties.getProperty("DBPASSWORD");
try {
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
if (conn != null) {
return conn;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

//关闭连接(没有打开的参数为null);
public void closeAll(Connection conn, Statement st, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}