JDBC数据库连接
这是一个数据库连接的工具类,单纯减少代码量和代码的规范性
package javaweb.com.JDBC;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JdbcUtilsDemo {
private static String url;
private static String user;
private static String password;
private static String driver;
// 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
static {
Properties pro = new Properties();
try {
//2. 加载文件
pro.load(new FileReader("C:\\Users\\syj\\IdeaProjects\\" +
"day04-code\\code\\src\\javaweb\\com\\jdbc.propertios"));
//3. 获取数据,赋值
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
// 注册驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//获取连接数据库
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
// 释放资源
public static void close(Statement stmt, Connection conn){
if (stmt!=null)
{
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null)
{
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn){
if (rs!=null)
{
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt!=null)
{
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null)
{
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}