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/jdbcstudy?useUnicode=true&characterEncoding=utf8
使用方法
import java.sql.*;
//import JdbcUtils;
/**
* @author Acx7
*/
public class JdbcTest {
public static void main(String[] args) {
Statement st = null;
ResultSet rs = null;
Connection conn = null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
String sql = "SELECT * FROM users";
rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getObject("id"));
}
// String sql = "INSERT INTO users(id,`name`) VALUES (4,'Acx7')";
// int result = st.executeUpdate(sql); // 返回受影响的行数
// String sql = "UPDATE users SET `name`='acx' WHERE id=4";
// int result = st.executeUpdate(sql); // 返回受影响的行数
// String sql = "DELETE FROM users WHERE id=3";
// int result = st.executeUpdate(sql); // 返回受影响的行数
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(rs, st, conn);
}
}
}