一、JDBC基础
连接数据的步骤:
1.注册驱动 :Class.forName(“com.MySQL.jdbc.Driver”)推荐这种方式,不会对具体的驱动类产生依赖;DriverManager.registerDriver(com.mysql.jdbc.Driver)会造成DriverManager中产生两个一样的驱动,并会对具体的驱动类产生依赖;System.setPRoperty(“jdbc.drivers”, “driver1:driver2”)虽然不会对具体的驱动类产生依赖;但注册不太方便,所以很少使用。 2.建立连接(Connection) :Connection conn = DriverManager.getConnection(url, user, passWord);url格式:JDBC:子协议:子名称//主机名:端口/数据库名?属性名=属性值&...;User,password可以用“属性名=属性值”方式告诉数据库;其他参数如:useUnicode=true&characterEncoding=GBK。3.创建执行SQL的语句(Statement):4.执行语句5.处理执行结果(ResultSet)6.释放资源
1、注册数据库驱动的方式:
1)加载 JDBC 驱动需调用 Class 类的静态方法 forName(),向其传递要加载的 JDBC 驱动的类名;
1 @Test 2 public void testDriverManager() throws Exception{ 3 //1. 准备连接数据库的 4 个字符串. 4 //驱动的全类名. 5 String driverClass = "com.mysql.jdbc.Driver"; 6 //JDBC URL 7 String jdbcUrl = "jdbc:mysql://localhost:3306/test"; 8 //user 9 String user = "root";10 //password11 String password = "123456";12 13 //2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)14 Class.forName(driverClass);15 16 //3. 通过 DriverManager 的 getConnection() 方法获取数据库连接. 17 Connection connection = 18 DriverManager.getConnection(jdbcUrl, user, password);19 System.out.println(connection); 20 21 }View Code
2)Driver 是一个接口: 数据库厂商必须提供实现的接口. 能从其中获取数据库连接.可以通过 Driver 的实现类对象获取数据库连接.
1 @Test 2 public void testDriver() throws SQLException { 3 //1. 创建一个 Driver 实现类的对象 4 Driver driver = new com.mysql.jdbc.Driver(); 5 6 //2. 准备连接数据库的基本信息: url, user, password 7 String url = "jdbc:mysql://localhost:3306/test"; 8 Properties info = new Properties(); 9 info.put("user", "root");10 info.put("password", "123456");11 12 //3. 调用 Driver 接口的 connect(url, info) 获取数据库连接13 Connection connection = driver.connect(url, info);14 System.out.println(connection);15 }View Code
2、获取数据库连接的方式:1)DriverManager 是驱动的管理类:1). 可以通过重载的 getConnection() 方法获取数据库连接. 较为方便,2). 可以同时管理多个驱动程序: 若注册了多个数据库连接, 则调用 getConnection(),3)方法时传入的参数不同, 即返回不同的数据库连接。
例:Connection connection =DriverManager.getConnection(jdbcUrl, user, password);
2)Driver 是一个接口: 数据库厂商必须提供实现的接口. 能从其中获取数据库连接.可以通过 Driver 的实现类对象获取数据库连接.
例:Connection connection = driver.connect(url, info);
3.创建执行SQL的语句(statement、preparedstatement):
通过 JDBC 向指定的数据表中插入一条记录. a. Statement: 用于执行 SQL 语句的对象 1). 通过 Connection 的 createStatement() 方法来获取 2). 通过 executeUpdate(sql) 可以执行 SQL 语句. 3). 传入的 SQL 可以是 INSRET, UPDATE 或 DELETE. 但不能是 SELECT b. Connection、Statement 都是应用程序和数据库服务器的连接资源. 使用后一定要关闭. 需要在 finally 中关闭 Connection 和 Statement 对象. c. 关闭的顺序是: 先关闭后获取的. 即先关闭 Statement 后关闭 Connection
示例代码如下:
1 @Test 2 public void testStatement() throws Exception{ 3 //1. 获取数据库连接 4 Connection conn = null; 5 Statement statement = null; 6 7 try { 8 conn = JDBCTools.getConnection(); 9 10 //3. 准备插入的 SQL 语句11 String sql = null;12 13 //sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) " +14 //"VALUES('XYZ', 'xyz@atguigu.com', '1990-12-12')";15 //sql = "DELETE FROM customers WHERE id = 1";16 sql = "UPDATE customers SET name = 'TOM' " +17 "WHERE id = 4";18 System.out.println(sql);19 20 //4. 执行插入. 21 //1). 获取操作 SQL 语句的 Statement 对象: 22 //调用 Connection 的 createStatement() 方法来获取23 statement = conn.createStatement();24 25 //2). 调用 Statement 对象的 executeUpdate(sql) 执行 SQL 语句进行插入26 statement.executeUpdate(sql);27 } catch (Exception e) {28 e.printStackTrace();29 } finally{30 JDBCTools.release(statement,conn);31 }View Code
4.处理执行结果(ResultSet):ResultSet: 结果集. 封装了使用 JDBC 进行查询的结果. a. 调用 Statement 对象的 executeQuery(sql) 可以得到结果集. b. ResultSet 返回的实际上就是一张数据表. 有一个指针指向数据表的第一样的前面.可以调用 next() 方法检测下一行是否有效. 若有效该方法返回 true, 且指针下移. 相当于Iterator 对象的 hasNext() 和 next() 方法的结合体 c. 当指针对位到一行时, 可以通过调用 getXxx(index) 或 getXxx(columnName),获取每一列的值. 例如: getInt(1), getString("name") d. ResultSet 当然也需要进行关闭.
示例代码如下:
1 @Test 2 public void testResultSet(){ 3 //获取 id=4 的 customers 数据表的记录, 并打印 4 5 Connection conn = null; 6 Statement statement = null; 7 ResultSet rs = null; 8 9 try {10 //1. 获取 Connection11 conn = JDBCTools.getConnection();12 System.out.println(conn);13 14 //2. 获取 Statement15 statement = conn.createStatement();16 System.out.println(statement);17 18 //3. 准备 SQL19 String sql = "SELECT id, name, email, birth " +20 "FROM customers";21 22 //4. 执行查询, 得到 ResultSet23 rs = statement.executeQuery(sql);24 System.out.println(rs);25 26 //5. 处理 ResultSet27 while(rs.next()){28 int id = rs.getInt(1);29 String name = rs.getString("name");30 String email = rs.getString(3);31 Date birth = rs.getDate(4);32 33 System.out.println(id);34 System.out.println(name);35 System.out.println(email);36 System.out.println(birth);37 }38 39 } catch (Exception e) {40 e.printStackTrace();41 } finally{42 //6. 关闭数据库资源. 43 JDBCTools.release(rs, statement, conn);44 }45 46 }View Code
JDBC工具模板(JDBCTools)配置如下:
1 import java.io.InputStream; 2 import java.sql.Connection; 3 import java.sql.DriverManager; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 import java.util.Properties; 8 9 /**10 * 操作 JDBC 的工具类. 其中封装了一些工具方法 Version 111 */12 public class JDBCTools {13 14 public static void release(ResultSet rs, 15 Statement statement, Connection conn) {16 if(rs != null){17 try {18 rs.close();19 } catch (SQLException e) {20 e.printStackTrace();21 }22 }23 24 25 if (statement != null) {26 try {27 statement.close();28 } catch (Exception e2) {29 e2.printStackTrace();30 }31 }32 33 if (conn != null) {34 try {35 conn.close();36 } catch (Exception e2) {37 e2.printStackTrace();38 }39 }40 }41 42 /**43 * 关闭 Statement 和 Connection44 * @param statement45 * @param conn46 */47 public static void release(Statement statement, Connection conn) {48 if (statement != null) {49 try {50 statement.close();51 } catch (Exception e2) {52 e2.printStackTrace();53 }54 }55 56 if (conn != null) {57 try {58 conn.close();59 } catch (Exception e2) {60 e2.printStackTrace();61 }62 }63 }64 65 /**66 * 1. 获取连接的方法. 通过读取配置文件从数据库服务器获取一个连接.67 * 68 * @return69 * @throws Exception70 */71 public static Connection getConnection() throws Exception {72 // 1. 准备连接数据库的 4 个字符串.73 // 1). 创建 Properties 对象74 Properties properties = new Properties();75 76 // 2). 获取 jdbc.properties 对应的输入流77 InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream(78 "jdbc.properties");79 80 // 3). 加载 2) 对应的输入流81 properties.load(in);82 83 // 4). 具体决定 user, password 等4 个字符串.84 String user = properties.getProperty("user");85 String password = properties.getProperty("password");86 String jdbcUrl = properties.getProperty("jdbcUrl");87 String driver = properties.getProperty("driver");88 89 // 2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)90 Class.forName(driver);91 92 // 3. 通过 DriverManager 的 getConnection() 方法获取数据库连接.93 return DriverManager.getConnection(jdbcUrl, user, password);94 }95 96 }View Code
1 driver=com.mysql.jdbc.Driver2 jdbcUrl=jdbc:mysql://localhost:3306/test3 user=root4 password=123456View Code
二、实现数据库增删改查
1.创立数据库表 examstudent;
1 /* 2 Navicat MySQL Data Transfer 3 4 Source Server : localhost 5 Source Server Version : 50524 6 Source Host : localhost:3306 7 Source Database : examstudent 8 9 Target Server Type : MYSQL10 Target Server Version : 5052411 File Encoding : 6500112 13 Date: 2015-06-27 15:49:2214 */15 16 SET FOREIGN_KEY_CHECKS=0;17 18 -- ----------------------------19 -- Table structure for examstudent20 -- ----------------------------21 DROP TABLE IF EXISTS `examstudent`;22 CREATE TABLE `examstudent` (23 `flowid` int(11) NOT NULL,24 `type` int(11) DEFAULT NULL,25 `idcard` varchar(18) DEFAULT NULL,26 `examcard` varchar(15) DEFAULT NULL,27 `studentname` varchar(20) DEFAULT NULL,28 `location` varchar(20) DEFAULT NULL,29 `grade` int(11) DEFAULT NULL,30 PRIMARY KEY (`flowid`)31 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;View Code
2.向数据库中添加如下数据
3. 在 eclipse 中建立 java 程序:输入身份证号或准考证号可以查询到学生的基本信息。
4.完成学生信息的删除功能
示例代码如下:
jdbc.properties
1 user=root2 password=1234563 driverClass=com.mysql.jdbc.Driver4 url=jdbc:mysql://localhost:3306/examstudentView Code
student.java
1 package com.atguigu.jdbc; 2 3 public class Student { 4 5 // 流水号 6 private int flowId; 7 // 考试的类型 8 private int type; 9 // 身份证号 10 private String idCard; 11 // 准考证号 12 private String examCard; 13 // 学生名 14 private String studentName; 15 // 学生地址 16 private String location; 17 // 考试分数. 18 private int grade; 19 20 public int getFlowId() { 21 return flowId; 22 } 23 24 public void setFlowId(int flowId) { 25 this.flowId = flowId; 26 } 27 28 public int getType() { 29 return type; 30 } 31 32 public void setType(int type) { 33 this.type = type; 34 } 35 36 public String getIdCard() { 37 return idCard; 38 } 39 40 public void setIdCard(String idCard) { 41 this.idCard = idCard; 42 } 43 44 public String getExamCard() { 45 return examCard; 46 } 47 48 public void setExamCard(String examCard) { 49 this.examCard = examCard; 50 } 51 52 public String getStudentName() { 53 return studentName; 54 } 55 56 public void setStudentName(String studentName) { 57 this.studentName = studentName; 58 } 59 60 public String getLocation() { 61 return location; 62 } 63 64 public void setLocation(String location) { 65 this.location = location; 66 } 67 68 public int getGrade() { 69 return grade; 70 } 71 72 public void setGrade(int grade) { 73 this.grade = grade; 74 } 75 76 public Student(int flowId, int type, String idCard, String examCard, 77 String studentName, String location, int grade) { 78 super(); 79 this.flowId = flowId; 80 this.type = type; 81 this.idCard = idCard; 82 this.examCard = examCard; 83 this.studentName = studentName; 84 this.location = location; 85 this.grade = grade; 86 } 87 88 public Student() { 89 // TODO Auto-generated constructor stub 90 } 91 92 @Override 93 public String toString() { 94 return "Student [flowId=" + flowId + ", type=" + type + ", idCard=" 95 + idCard + ", examCard=" + examCard + ", studentName=" 96 + studentName + ", location=" + location + ", grade=" + grade 97 + "]"; 98 } 99 100 }View Code
JDBCTools.java
1 package cky.test; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.PreparedStatement; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 import java.sql.Statement; 11 import java.util.Properties; 12 13 public class JDBCTools { 14 15 /** 16 * 执行 SQL 语句, 使用 PreparedStatement 17 * @param sql 18 * @param args: 填写 SQL 占位符的可变参数 19 */ 20 public static void update(String sql, Object ... args){ 21 Connection connection = null; 22 PreparedStatement preparedStatement = null; 23 24 try { 25 connection = JDBCTools.getConnection(); 26 preparedStatement = connection.prepareStatement(sql); 27 28 for(int i = 0; i < args.length; i++){ 29 preparedStatement.setObject(i + 1, args[i]); 30 } 31 32 preparedStatement.executeUpdate(); 33 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } finally{ 37 JDBCTools.releaseDB(null, preparedStatement, connection); 38 } 39 } 40 41 /** 42 * 执行 SQL 的方法 43 * 44 * @param sql: insert, update 或 delete。 而不包含 select 45 */ 46 public static void update(String sql) { 47 Connection connection = null; 48 Statement statement = null; 49 50 try { 51 // 1. 获取数据库连接 52 connection = getConnection(); 53 54 // 2. 调用 Connection 对象的 createStatement() 方法获取 Statement 对象 55 statement = connection.createStatement(); 56 57 // 4. 发送 SQL 语句: 调用 Statement 对象的 executeUpdate(sql) 方法 58 statement.executeUpdate(sql); 59 60 } catch (Exception e) { 61 e.printStackTrace(); 62 } finally { 63 // 5. 关闭数据库资源: 由里向外关闭. 64 releaseDB(null, statement, connection); 65 } 66 } 67 68 /** 69 * 释放数据库资源的方法 70 * 71 * @param resultSet 72 * @param statement 73 * @param connection 74 */ 75 public static void releaseDB(ResultSet resultSet, Statement statement, 76 Connection connection) { 77 78 if (resultSet != null) { 79 try { 80 resultSet.close(); 81 } catch (SQLException e) { 82 e.printStackTrace(); 83 } 84 } 85 86 if (statement != null) { 87 try { 88 statement.close(); 89 } catch (SQLException e) { 90 e.printStackTrace(); 91 } 92 } 93 94 if (connection != null) { 95 try { 96 connection.close(); 97 } catch (SQLException e) { 98 e.printStackTrace(); 99 }100 }101 102 }103 104 /**105 * 获取数据库连接的方法106 */107 public static Connection getConnection() throws IOException,108 ClassNotFoundException, SQLException {109 // 0. 读取 jdbc.properties110 /**111 * 1). 属性文件对应 Java 中的 Properties 类 2). 可以使用类加载器加载 bin 目录(类路径下)的文件112 */113 Properties properties = new Properties();114 InputStream inStream = JDBCTools.class.getClassLoader()115 .getResourceAsStream("jdbc.properties");116 properties.load(inStream);117 118 // 1. 准备获取连接的 4 个字符串: user, password, jdbcUrl, driverClass119 String user = properties.getProperty("user");120 String password = properties.getProperty("password");121 String jdbcUrl = properties.getProperty("url");122 String driverClass = properties.getProperty("driverClass");123 124 // 2. 加载驱动: Class.forName(driverClass)125 Class.forName(driverClass);126 127 // 3. 调用128 // DriverManager.getConnection(jdbcUrl, user, password)129 // 获取数据库连接130 Connection connection = DriverManager.getConnection(jdbcUrl, user,131 password);132 return connection;133 }134 135 }View Code
JDBCTest.java
1 package cky.test; 2 3 import java.sql.Connection; 4 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 8 import java.util.Scanner; 9 10 import org.junit.Test; 11 12 public class JDBCTest { 13 14 //得到学生的信息集 15 public Student getStudent(String sql, Object... args) { 16 Student stu = null; 17 18 Connection connection = null; 19 PreparedStatement preparedStatement = null; 20 ResultSet resultSet = null; 21 22 try { 23 connection = JDBCTools.getConnection(); 24 preparedStatement = connection.prepareStatement(sql); 25 for (int i = 0; i < args.length; i++) { 26 preparedStatement.setObject(i + 1, args[i]); 27 } 28 resultSet = preparedStatement.executeQuery(); 29 30 if (resultSet.next()) { 31 stu = new Student(); 32 stu.setFlowId(resultSet.getInt(1)); 33 stu.setType(resultSet.getInt(2)); 34 stu.setIdCard(resultSet.getString(3)); 35 36 } 37 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } finally { 41 JDBCTools.releaseDB(resultSet, preparedStatement, connection); 42 } 43 44 return stu; 45 } 46 47 48 /* 49 private Student getStudent(String sql) { 50 51 Student stu = null; 52 53 Connection connection = null; 54 Statement statement = null; 55 ResultSet resultSet = null; 56 57 try { 58 connection = JDBCTools.getConnection(); 59 statement = connection.createStatement(); 60 resultSet = statement.executeQuery(sql); 61 62 if (resultSet.next()) { 63 stu = new Student(resultSet.getInt(1), resultSet.getInt(2), 64 resultSet.getString(3), resultSet.getString(4), 65 resultSet.getString(5), resultSet.getString(6), 66 resultSet.getInt(7)); 67 } 68 69 } catch (Exception e) { 70 e.printStackTrace(); 71 } finally { 72 JDBCTools.releaseDB(resultSet, statement, connection); 73 } 74 75 return stu; 76 } 77 */ 78 79 //打印学生信息: 若学生存在则打印其具体信息. 若不存在: 打印查无此人 80 private void printStudent(Student student) { 81 if (student != null) { 82 System.out.println(student); 83 } else { 84 System.out.println("查无此人!"); 85 } 86 } 87 88 // 从控制台读入一个整数, 确定要查询的类型; @return: 1. 用身份证查询. 2. 用准考证号查询 其他的无效. 并提示请用户重新输入. 89 private int getSearchTypeFromConsole() { 90 91 System.out.print("请输入查询类型: 1. 用身份证查询. 2. 用准考证号查询 "); 92 93 Scanner scanner = new Scanner(System.in); 94 int type = scanner.nextInt(); 95 96 if (type != 1 && type != 2) { 97 System.out.println("输入有误请重新输入!"); 98 throw new RuntimeException(); 99 }100 101 return type;102 }103 104 //从控制台输入学生的信息105 private Student getStudentFromConsole() {106 107 Scanner scanner = new Scanner(System.in);108 109 Student student = new Student();110 111 System.out.print("FlowId:");112 student.setFlowId(scanner.nextInt());113 114 System.out.print("Type: ");115 student.setType(scanner.nextInt());116 117 System.out.print("IdCard:");118 student.setIdCard(scanner.next());119 120 System.out.print("ExamCard:");121 student.setExamCard(scanner.next());122 123 System.out.print("StudentName:");124 student.setStudentName(scanner.next());125 126 System.out.print("Location:");127 student.setLocation(scanner.next());128 129 System.out.print("Grade:");130 student.setGrade(scanner.nextInt());131 132 return student;133 }134 135 public void addNewStudent2(Student student) {136 String sql = "INSERT INTO examstudent(flowid, type, idcard, "137 + "examcard, studentname, location, grade) "138 + "VALUES(?,?,?,?,?,?,?)";139 140 JDBCTools.update(sql, student.getFlowId(), student.getType(),141 student.getIdCard(), student.getExamCard(),142 student.getStudentName(), student.getLocation(),143 student.getGrade());144 }145 146 /*147 public void addNewStudent(Student student) {148 // 1. 准备一条 SQL 语句:149 String sql = "INSERT INTO examstudent VALUES(" + student.getFlowId()150 + "," + student.getType() + ",'" + student.getIdCard() + "','"151 + student.getExamCard() + "','" + student.getStudentName()152 + "','" + student.getLocation() + "'," + student.getGrade()153 + ")";154 155 System.out.println(sql);156 157 // 2. 调用 JDBCTools 类的 update(sql) 方法执行插入操作.158 JDBCTools.update(sql);159 }160 */161 162 //具体查询学生信息的. 返回一个 Student 对象. 若不存在, 则返回 null163 private Student searchStudent(int searchType) {164 165 String sql = "SELECT flowid, type, idcard, examcard,"166 + "studentname, location, grade " + "FROM examstudent "167 + "WHERE ";168 169 Scanner scanner = new Scanner(System.in);170 171 // 1. 根据输入的 searchType, 提示用户输入信息:172 // 1.1 若 searchType 为 1, 提示: 请输入身份证号. 若为 2 提示: 请输入准考证号173 // 2. 根据 searchType 确定 SQL174 if (searchType == 1) {175 System.out.print("请输入准考证号:");176 String examCard = scanner.next();177 sql = sql + "examcard = '" + examCard + "'";178 } else {179 System.out.print("请输入身份证号:");180 String examCard = scanner.next();181 sql = sql + "idcard = '" + examCard + "'";182 }183 184 // 3. 执行查询185 Student student = getStudent(sql);186 187 // 4. 若存在查询结果, 把查询结果封装为一个 Student 对象188 189 return student;190 }191 192 193 //测试打印查询到的学生信息194 @Test195 public void testGetStudent() {196 // 1. 得到查询的类型197 int searchType = getSearchTypeFromConsole();198 199 // 2. 具体查询学生信息200 Student student = searchStudent(searchType);201 202 // 3. 打印学生信息203 printStudent(student);204 }205 206 207 @Test208 public void testAddNewStudent() {209 Student student = getStudentFromConsole();210 addNewStudent2(student);211 }212 213 }View Code
三、Statement 与 ResultSet1.通过调用 Connection 对象的 createStatement 方法创建该对象? Statement st = conn.createStatement();2.该对象用于执行静态的 SQL 语句,并且返回执行结果3.Statement 接口中定义了下列方法用于执行 SQL 语句:? ResultSet excuteQuery(String sql)? int excuteUpdate(String sql)
通用的INSERT、UPDATA、DELETE方法
1 //通用的 INSSERT UPDATE DELETE 方法(version 1.0) 2 public void update(String sql){ 3 //1.获取数据库的连接 4 Connection conn = null; 5 Statement st = null; 6 try{ 7 conn = JDBCUtils.getConnection(); 8 //2.提供一个 Statement 对象,将 sql 传递给数据库中执行 9 st = conn.createStatement();10 st.execute(sql);11 }catch(Exception e){12 e.printStackTrace();13 }finally{14 //3.关闭 Statement 对象及连接15 JDBCUtils.close(null, st, conn);16 } 17 }View Code
通用的查询方法,返回一个对象
1 public <T> T get(String sql, Class<T> clazz) { 2 Connection conn = null; 3 Statement st = null; 4 ResultSet rs = null; 5 T t = null; 6 try { 7 t = clazz.newInstance(); 8 conn = JDBCUtils.getConnection(); 9 st = conn.createStatement();10 rs = st.executeQuery(sql);11 /*12 * 通过 ResultSet 调用 getMetaData()返回一个结果集的元数据:ResultSetMetaData13 *14 * 1.getColumnCount():返回结果集的列数15 * 2.getColumnLabel():返回列的别名16 */17 ResultSetMetaData rsmd = rs.getMetaData();18 int columnCount = rsmd.getColumnCount();19 if (rs.next()) {20 for (int i = 0; i < columnCount; i++) {21 Object columnVal = rs.getObject(i + 1);// 相应列的值22 //String columnName = rsmd.getColumnName(i + 1);23 String columnName = rsmd.getColumnLabel(i + 1);24 //使用 PropertyUtils 将指定对象 t 的指定属性 columnName 设置为指定的值 columnVal25 PropertyUtils.setProperty(t, columnName, columnVal);26 } 27 }28 } catch (Exception e) {29 e.printStackTrace();30 } finally {31 JDBCUtils.close(rs, st, conn);32 }33 return t;34 }View Code
//通用的返回多个对象的查询操作
1 public <T> List<T> getInstances(String sql,Class<T> clazz){ 2 Connection conn = null; 3 Statement st = null; 4 ResultSet rs = null; 5 List<T> list = new ArrayList<T>(); 6 try { 7 conn = JDBCUtils.getConnection(); 8 st = conn.createStatement(); 9 rs = st.executeQuery(sql);10 /*11 * 通过 ResultSet 调用 getMetaData()返回一个结果集的元数据:ResultSetMetaData12 *13 * 1.getColumnCount():返回结果集的列数14 * 2.getColumnLabel():返回列的别名15 */16 ResultSetMetaData rsmd = rs.getMetaData();17 int columnCount = rsmd.getColumnCount();18 while (rs.next()) {19 T t = clazz.newInstance();20 for (int i = 0; i < columnCount; i++) {21 Object columnVal = rs.getObject(i + 1);// 相应列的值22 //String columnName = rsmd.getColumnName(i + 1);23 String columnName = rsmd.getColumnLabel(i + 1);24 //使用 PropertyUtils 将指定对象 t 的指定属性 columnName 设置为指定的值 columnVal25 PropertyUtils.setProperty(t, columnName, columnVal);26 }27 list.add(t);28 }29 } catch (Exception e) {30 e.printStackTrace();31 } finally {32 JDBCUtils.close(rs, st, conn);33 }34 return list;35 }View Code
或者采用这个方法(个人比较喜欢)
1 public List<Map<String, Object>>
新闻热点
疑难解答