JDBC连接数据库的工具包代码

时间:2022-02-21 16:06:09
package donghongyu.tk.news.util;

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

//进行连接,
public class JdbcUtil {
private static Connection conn;

private JdbcUtil() {
super();
// TODO Auto-generated constructor stub
}

//返回连接对象
public static synchronized Connection getConn() {
if (conn == null) {
try {
// 加载驱动文件

Class.forName("com.mysql.jdbc.Driver");
// 将属性文件加载
File file = new File("src/jdbc.properties");
// 将文件转化为输入流
InputStream is = new FileInputStream(file);
// 创建属性对象
Properties prop = new Properties();
// 将属性流加载到属性对象中
prop.load(is);

// 创建连接从属性文件取出相应值连接
conn = DriverManager.getConnection(prop.getProperty("url"),
prop.getProperty("user"), prop.getProperty("pass"));

} catch (ClassNotFoundException | IOException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return conn;
}


//关闭资源就行释放
public static void release(Statement pstmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}