简介
在进行后端业务开发大量使用ORM框架的情况下,已经很少有机会直接使用到JDBC进行数据的写入查询了。
最近正好有机会,于是整理码了一个JdbcUtils工具类,包含数据源连接、断连、数据查询、数据更新及命令执行,方便直接使用Jdbc进行数据操作。
设计
废话不多说,直接上完整源码:
JdbcUtils.java
1 | import org.slf4j.Logger; |
用法示例
执行命令
代码1
2
3
4
5
6
7Connection connection = JdbcUtils.connect(Driver.class.getCanonicalName(), "jdbc:mysql://192.168.100.203:3306/test_commons?useSSL=false", "root", "123456");
System.out.println(JdbcUtils.execute(connection, "create table test(\n" +
"id int(11) not null auto_increment primary key,\n" +
"name varchar(255) null,\n" +
"description text null\n" +
")"));
JdbcUtils.disconnect(connection);
运行结果1
true
新增
代码1
2
3Connection connection = JdbcUtils.connect(Driver.class.getCanonicalName(), "jdbc:mysql://192.168.100.203:3306/test_commons?useSSL=false", "root", "123456");
System.out.println(JdbcUtils.update(connection, "insert into test(name,description) values(?, ?)", "Johnson-1", "test-description-1"));
JdbcUtils.disconnect(connection);
运行结果1
1
更新
代码1
2
3Connection connection = JdbcUtils.connect(Driver.class.getCanonicalName(), "jdbc:mysql://192.168.100.203:3306/test_commons?useSSL=false", "root", "123456");
System.out.println(JdbcUtils.update(connection, JdbcUtils.buildCommand("update test set description = ? where name = ?", "abc-1", "johnson-1")));
JdbcUtils.disconnect(connection);
运行结果1
1
删除
代码1
2
3Connection connection = JdbcUtils.connect(Driver.class.getCanonicalName(), "jdbc:mysql://192.168.100.203:3306/test_commons?useSSL=false", "root", "123456");
System.out.println(JdbcUtils.update(connection, JdbcUtils.Command.build().sql("delete from test where name = ?").params("johnson-1")));
JdbcUtils.disconnect(connection);
运行结果1
1
查询
代码1
2
3Connection connection = JdbcUtils.connect(Driver.class.getCanonicalName(), "jdbc:mysql://192.168.100.203:3306/test_commons?useSSL=false", "root", "123456");
JdbcUtils.query(connection, JdbcUtils.buildCommand("select * from test"), (row, rowNumber) -> System.out.println(String.format("row: %s, data: %s", rowNumber, row)));
JdbcUtils.disconnect(connection);
运行结果1
2
3row: 1, data: {id=2, name=Johnson-1, description=test-description-1}
row: 2, data: {id=3, name=Johnson-2, description=test-description-2}
row: 3, data: {id=4, name=Johnson-3, description=test-description-3}
执行事务
代码1
2
3
4
5Connection connection = JdbcUtils.connect(Driver.class.getCanonicalName(), "jdbc:mysql://192.168.100.203:3306/test_commons?useSSL=false", "root", "123456");
System.out.println(JdbcUtils.transaction(connection,
JdbcUtils.buildCommand("insert into test(name,description) values(?, ?)", "Johnson-4", "test-description-4"),
JdbcUtils.buildCommand("insert into test(name,description) values(?, ?)", "Johnson-5", "test-description-5")));
JdbcUtils.disconnect(connection);
运行结果1
true