当前位置:网站首页>JDBC revisited
JDBC revisited
2022-08-02 06:04:00 【so sleepy tomato】
文章目录
1.JDBC程序的编写步骤

- 加载并注册驱动(Different databases have different drivers(Equivalent to a class implemented by each database vendor))
- 创建Connection连接对象(连接数据库)
- 创建Statement或者PreparedStatement对象
- 执行SQL语句
- 使用ResultSet收集对象、关闭ResultSet对象(If it is an addition, deletion or modification, it is not necessary)
- 关闭Statement或者PreparedStatement对象
2.加载驱动,获取连接
public class ConnectionTest {
// 获取连接对象
@Test
public void test1() throws Exception{
InputStream resourceAsStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driverClass");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username,password);
System.out.println(connection);
}
}
3.创建Statement或者PraparedStatement对象
Connection.Statement();
Connection.prepareStatement(sql);
4.The overall complete process
4.1针对增删改操作
@Test
public void test2(){
Connection connection = null;
PreparedStatement ps = null;
try {
InputStream resourceAsStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driverClass");
// 1.注册驱动
Class.forName(driver);
// 2.获取连接
connection = DriverManager.getConnection(url, username,password);
// 3.SQL语句
String sql = "insert into customers(name,email,birth)values(?,?,?)";// ?是占位符
ps = connection.prepareStatement(sql);
// 替换占位符(下标从1开始)
ps.setString(1, "李四");
ps.setString(2, "[email protected]");
ps.setDate(3,new java.sql.Date(new Date().getTime()));
// 执行语句
int updateRow = ps.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4.2针对查询操作
@Test
public void test3(){
Connection connection = null;
PreparedStatement ps = null;
try {
InputStream resourceAsStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driverClass");
// 1.注册驱动
Class.forName(driver);
// 2.获取连接
connection = DriverManager.getConnection(url, username,password);
// 3.SQL语句
String sql = "select * from customers";// ?是占位符
ps = connection.prepareStatement(sql);
// 4.执行语句
ResultSet resultSet = ps.executeQuery();
ArrayList<User> list = new ArrayList<User>();
while(resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setBirth(resultSet.getDate("birth"));
user.setPhoto(resultSet.getBlob("photo"));
list.add(user);
}
list.forEach(System.out::println);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
5.工具类封装
public class JDBCUtil {
private static Connection getConnection() throws Exception {
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(inputStream);
String username = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driverClass");
// 1.注册驱动
Class.forName(driver);
// 2.获取连接
Connection connection = DriverManager.getConnection(url, username,password);
return connection;
}
private static void close(Connection conn, PreparedStatement ps, ResultSet rs) throws Exception{
if(conn != null) {
conn.close();
}
if(ps != null) {
ps.close();
}
if(rs != null) {
rs.close();
}
}
/** * 增删改通用 * @return * @throws Exception */
public static int update(String sql, Object ...args) {
int executeUpdate = 0;
Connection connection = null;
PreparedStatement prepareStatement = null;
try {
connection = getConnection();
prepareStatement = connection.prepareStatement(sql);
for(int i = 0; i< args.length; i ++) {
prepareStatement.setObject(i+1, args[i]);
}
executeUpdate = prepareStatement.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
close(connection,prepareStatement,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return executeUpdate;
}
public static <T> List<T> query(String sql,Class clazz,Object ...args){
List<T> list = null;
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet executeQuery = null;
try {
connection = getConnection();
prepareStatement = connection.prepareStatement(sql);
for(int i = 0; i< args.length; i ++) {
prepareStatement.setObject(i+1, args[i]);
}
executeQuery = prepareStatement.executeQuery();
ResultSetMetaData metaData = executeQuery.getMetaData();
int columnCount = metaData.getColumnCount();
list = new ArrayList<T>();
while(executeQuery.next()) {
T t = (T) clazz.newInstance();
for(int i = 0; i < columnCount; i++) {
String key = metaData.getColumnLabel(i+1);
Object value = executeQuery.getObject(i+1);
Field field = clazz.getDeclaredField(key);
field.setAccessible(true);
field.set(t, value);
}
list.add(t);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
close(connection,prepareStatement,executeQuery);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
}
6.数据库事务
事务:一组SQL语句是一个整体,要么都执行,要么都不执行.
Consider the code implementation after the transaction:
执行sqlput before the statementmysqlThe default commit feature is turned off,在执行多个sqlA connection cannot be closed in the middle of a statement,If an exception occurs in the middle, it must be rolled backsql
public class TranslationTest {
@Test
public void test1() {
Connection connection = null;
try {
connection = JDBCUtil.getConnection();
// 1.关闭自动提交
connection.setAutoCommit(false);
String sql1 = "update user_table set balance = balance - 100 where user = ?";
update(connection,sql1,"AA");
int i = 5 / 0;
String sql2 = "update user_table set balance = balance + 100 where user = ?";
update(connection,sql2,"BB");
connection.commit();
System.out.println("success");
} catch (Exception e) {
// TODO Auto-generated catch block
// 回滚
try {
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
// 关闭连接
JDBCUtil.close(connection, null, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/** * 增删改通用 * @return * @throws Exception */
public int update(Connection connection,String sql, Object ...args) throws Exception{
int executeUpdate = 0;
PreparedStatement prepareStatement = null;
prepareStatement = connection.prepareStatement(sql);
for(int i = 0; i< args.length; i ++) {
prepareStatement.setObject(i+1, args[i]);
}
executeUpdate = prepareStatement.executeUpdate();
JDBCUtil.close(null,prepareStatement,null);
return executeUpdate;
}
}
ent prepareStatement = null;
prepareStatement = connection.prepareStatement(sql);
for(int i = 0; i< args.length; i ++) {
prepareStatement.setObject(i+1, args[i]);
}
executeUpdate = prepareStatement.executeUpdate();
JDBCUtil.close(null,prepareStatement,null);
return executeUpdate;
}
}
边栏推荐
- interrupt()、interrupted()和isInterrupted()你真的懂了吗
- 力扣练习——单词搜索
- Crawler_crawl wasde monthly supply and demand balance table (example)
- pg数据库报错问题,有懂的吗
- RADIUS 如何提高 WiFi 无线网络安全性?
- Digicert EV证书签名后出现“证书对于请求用法无效”的解决方案
- [QNX Hypervisor 2.2用户手册]9.17 tolerance
- 【疑问】最终推荐的loose pattern 如果依赖module 没有加载完毕,行为如何,是否报错
- SQL数据表增加列
- 使用pycharm debug 深度学习代码
猜你喜欢
随机推荐
The line chart with square PyQt5_pyqtgraph mouse
MySQL 灵魂 16 问,你能撑到第几问?
vs2022 编译libmodbus源码
Nuscenes数据集总结(下)
MySQL 字符串拼接 - 多种字符串拼接实战案例
简道云-灵活易用的应用搭建平台
【Gazebo入门教程】第一讲 Gazebo的安装、UI界面、SDF文件介绍
PyQt5_pyqtgraph mouse draws straight lines on line charts
转:张五常:比知识更重要的,是思维方式
其他重要协议(DNS,ICMP,NAT,交换机)
软件测试分析流程及输出项包括哪些内容?
CubeSat Light-1
腾讯注册中心演进及性能优化实践
你要的在这里,自己维护的石墨文档
递归实现指数型枚举(DAY 91)
[网鼎杯 2020 青龙组]singal
关于地图GIS的一次实践整理(下) Redis的GIS实践
力扣练习——41 对称二叉树
2022河南萌新联赛第(四)场:郑州轻工业大学 A - ZZULI
UE4 局域网联机案例









