一、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 Code2)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 Code2、獲取數據庫連接的方式: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 Code4.處理執行結果(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 CodeJDBC工具模板(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 CodeJDBCTools.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 CodeJDBCTest.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>>
新聞熱點
疑難解答