/**
*
* @Description 操作数据库的工具类
* @author lxd Email:3263617383@qq.com
* @version
* @date 2022年3月10日下午12:04:12
*
*/
public class JDBCUtils {
/**
*
* @Description 获取数据库的连接
* @author lxd
* @date 2022年3月10日下午12:07:34
* @return
* @throws IOException
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
// 1.读取配置文件中的4个基本信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String dirverClass = pros.getProperty("driverClass");
// 加载驱动
Class.forName(dirverClass);
// 获取连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
/**
*
* @Description 关闭连接和Statement的操作
* @author lxd
* @date 2022年3月10日下午12:11:07
* @param conn
* @param ps
*/
public static void closeResource(Connection conn, Statement ps) {
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
通用的增删改操作
// 通用的增删改操作:
public void update(String sql, Object... args) { // sql中占位符个数与可变性惨的长度相同!
// 获取连接
Connection conn = null;
// 预编译sql语句
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
// 执行
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}
// 关闭资源
JDBCUtils.closeResource(conn, ps);
}