查看“使用PreparedStatement针对不同表的通用查询操作”的源代码
←
使用PreparedStatement针对不同表的通用查询操作
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看和复制此页面的源代码。
https://www.bilibili.com/video/BV1eJ411c7rf?p=21<syntaxhighlight lang="java"> import io.github.jihch.bean.Customer; import io.github.jihch.bean.Order; import io.github.jihch.util.JDBCUtils; import org.junit.Test; import java.lang.reflect.Field; import java.sql.*; import java.util.HashMap; import java.util.Map; /** * 使用 PreparedStatement 实现针对于不同表的通用的查询操作 */ public class PreparedStatementQueryTest { @Test public void testGetInstance() { String sql = "select id, name, email from customers where id = ?"; Customer customer = getInstance(Customer.class, sql, 2); System.out.println(customer); sql = "select order_id orderId, order_name orderName from `order` where order_id = ?"; Order order = getInstance(Order.class, sql, 1); System.out.println(order); } public <T> T getInstance(Class<T> clazz, String sql, Object... args) { T t = null; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } //执行获取结果集 rs = ps.executeQuery(); //获取结果集的元数据 ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); if (rs.next()) { t = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { //获取每个列的列值:通过ResultSet Object value = rs.getObject(i + 1); //获取每个列的列名:通过ResultSetMetaData //获取列的列名:getColumnName() --不推荐使用 //获取列的别名:getColumnLabel() String columnName = rsmd.getColumnName(i + 1); String columnLabel = rsmd.getColumnLabel(i + 1); System.out.printf("columnName:%s, columnLabel:%s\n", columnName, columnLabel); //通过反射,将对象指定名 columnName 的属性赋值为指定的值 columnValue // Field field = Order.class.getDeclaredField(columnName); Field field = clazz.getDeclaredField(columnLabel); field.setAccessible(true); field.set(t, value); } //获取每个列的列名 }//end if } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { JDBCUtils.closeResource(conn, ps, rs); } return t; } } </syntaxhighlight><syntaxhighlight lang="console"> columnName:id, columnLabel:id columnName:name, columnLabel:name columnName:email, columnLabel:email Customer{id=2, name='汪峰', email='wf@126.com', birth=null} columnName:order_id, columnLabel:orderId columnName:order_name, columnLabel:orderName Order{orderId=1, orderName='DD', orderDate=null} </syntaxhighlight>https://github.com/jihch/jdbc/blob/main/src/main/java/io/github/jihch/preparedstatement/crud/PreparedStatementQueryTest.java https://www.bilibili.com/video/BV1eJ411c7rf?p=22 === 封装通用查询列表 === <syntaxhighlight lang="java"> import io.github.jihch.bean.Customer; import io.github.jihch.bean.Order; import io.github.jihch.util.JDBCUtils; import org.junit.Test; import java.lang.reflect.Field; import java.sql.*; import java.util.*; import java.util.stream.Collectors; /** * 使用 PreparedStatement 实现针对于不同表的通用的查询操作 */ public class PreparedStatementQueryTest { @Test public void testGetForList3() { String sql = "SELECT * FROM jdbc_test.customers"; List<Customer> list = getForList(Customer.class, sql); list.forEach(System.out::println); } public <T> List<T> getForList(Class<T> clazz, String sql, Object... args) { List<T> list = new ArrayList<>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } //执行获取结果集 rs = ps.executeQuery(); //获取结果集的元数据 ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); Map<String, Field> fieldMap = Arrays.asList(clazz.getDeclaredFields()).stream().collect(Collectors.toMap(f -> f.getName(), f->f)); while (rs.next()) { T t = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { //获取每个列的列值:通过ResultSet Object value = rs.getObject(i + 1); //获取每个列的列名:通过ResultSetMetaData //获取列的列名:getColumnName() --不推荐使用 //获取列的别名:getColumnLabel() String columnName = rsmd.getColumnName(i + 1); String columnLabel = rsmd.getColumnLabel(i + 1); System.out.printf("columnName:%s, columnLabel:%s\n", columnName, columnLabel); //通过反射,将对象指定名 columnName 的属性赋值为指定的值 columnValue if (fieldMap.containsKey(columnLabel)) { Field field = clazz.getDeclaredField(columnLabel); field.setAccessible(true); field.set(t, value); } } //获取每个列的列名 list.add(t); }//end if } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { JDBCUtils.closeResource(conn, ps, rs); } return list; } } </syntaxhighlight><syntaxhighlight lang="console"> columnName:id, columnLabel:id columnName:name, columnLabel:name columnName:email, columnLabel:email columnName:birth, columnLabel:birth columnName:photo, columnLabel:photo columnName:id, columnLabel:id columnName:name, columnLabel:name columnName:email, columnLabel:email columnName:birth, columnLabel:birth columnName:photo, columnLabel:photo Customer{id=2, name='汪峰', email='wf@126.com', birth=2010-02-02} Customer{id=3, name='章子怡', email='zzy@gmail.com', birth=2001-02-02} </syntaxhighlight>
返回至
使用PreparedStatement针对不同表的通用查询操作
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
Spring Boot 2 零基础入门
Spring Cloud
Spring Boot
设计模式之禅
VUE
Vuex
Maven
算法
技能树
Wireshark
IntelliJ IDEA
ElasticSearch
VirtualBox
软考
正则表达式
程序员精讲
软件设计师精讲
初级程序员 历年真题
C
SQL
Java
FFmpeg
Redis
Kafka
MySQL
Spring
Docker
JMeter
Apache
Linux
Windows
Git
ZooKeeper
设计模式
Python
MyBatis
软件
数学
PHP
IntelliJ IDEA
CS基础知识
网络
项目
未分类
MediaWiki
镜像
问题
健身
国债
英语
烹饪
常见术语
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息