JDBC 封装
使用 JDBC 连接 MySQL 数据库,我们每次操作都要写一堆连接数据库的信息,操作完还要释放一堆资源,做了很多重复的工作,于是我们通常把数据库连接封装成工具类。
JdbcUtils 类
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.sql.*;
/**
* @author Acx7
*/
public class JdbcUtils {
private static String username = null;
private static String password = null;
private static String url = null;
static {
try {
// 加载配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("resources/db.properties"));
// 获取配置文件信息
String driver = properties.getProperty("driver");
username = properties.getProperty("username");
password = properties.getProperty("password");
url = properties.getProperty("url");
// 加载驱动
Class.forName(driver);
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
/**
* 获取连接对象
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
/**
* 释放资源
*/
public static void close(Statement ps, Connection conn) {
close(null, ps, conn);
}
/**
* 释放资源
*/
public static void close(ResultSet rs, Statement ps, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
配置文件
driver=com.mysql.jdbc.Driver
username=root
password=123456
url=jdbc:mysql://127.0.0.1:3306/databasename?useUnicode=true&characterEncoding=utf8
使用示例
import java.sql.*;
//import JdbcUtils;
/**
* @author Acx7
*/
public class JdbcTest {
public static void main(String[] args) {
PreparedStatement ps = null;
ResultSet rs = null;
Connection conn = null;
try {
conn = JdbcUtils.getConnection();
String sql = "SELECT `name` FROM users WHERE id=?";
ps = conn.prepareStatement(sql);
ps.setInt(1,1);
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getObject("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(rs, ps, conn);
}
}
}