查看“针对customers表的通用查询操作举例”的源代码
←
针对customers表的通用查询操作举例
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看和复制此页面的源代码。
https://www.bilibili.com/video/BV1eJ411c7rf?p=18<syntaxhighlight lang="java"> import io.github.jihch.bean.Customer; import io.github.jihch.util.JDBCUtils; import org.junit.Test; import java.lang.reflect.Field; import java.sql.*; /** * 针对于 Customers 表的查询操作 */ public class CustomerForQuery { @Test public void testQueryForCustomers() { String sql = "select id, name, email, birth from customers where id = ?"; Customer customer = queryForCustomers(sql, 2); System.out.println(customer); sql = "select name, email from customers where id = ?"; customer = queryForCustomers(sql, 2); System.out.println(customer); } /** * 针对 customers表的通用的查询操作 * @param sql * @param args * @throws Exception */ public Customer queryForCustomers(String sql, Object... args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Customer customer = 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(); //通过 ResultSetMetaData 获取结果集中的列数 int columnCount = rsmd.getColumnCount(); if (rs.next()) { customer = new Customer(); //处理结果集一行数据中的每一列 for (int i = 0; i < columnCount; i++) { //获取每个列的列名 String columnName = rsmd.getColumnName(i+1); Object columnValue = rs.getObject(i + 1); //给 customer 对象指定的某个属性,赋值为 value Field field = Customer.class.getDeclaredField(columnName); field.setAccessible(true); field.set(customer, columnValue); } }//end if } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { JDBCUtils.closeResource(conn, ps, rs); } return customer; } } </syntaxhighlight><syntaxhighlight lang="console"> Customer{id=2, name='汪峰', email='wf@126.com', birth=2010-02-02} Customer{id=0, name='汪峰', email='wf@126.com', birth=null} </syntaxhighlight>https://github.com/jihch/jdbc/blob/main/src/main/java/io/github/jihch/preparedstatement/crud/CustomerForQuery.java
返回至
针对customers表的通用查询操作举例
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
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帮助
工具
链入页面
相关更改
特殊页面
页面信息