JDBC学习笔记02【ResultSet类详解、JDBC登录案例练习、PreparedStatement类详解】
- 黑馬程序員-JDBC文檔(騰訊微云)JDBC筆記.pdf:https://share.weiyun.com/Kxy7LmRm
目錄
04?ResultSet類詳解
JDBC各個類詳解_ResultSet_基本使用
JDBC各個類詳解_ResultSet_遍歷
05?JDBC登錄案例練習
JDBC練習_select語句
Emp.java //?封裝Emp表數據的JavaBean
JDBCDemo8.java
JDBC工具類
JDBC練習_登錄案例
06?PreparedStatement類詳解
JDBC各個類詳解_PreparedStatement
登錄案例——解決sql注入問題
04?ResultSet類詳解
JDBC各個類詳解_ResultSet_基本使用
4. ResultSet:結果集對象,封裝查詢結果
?? ??? ?* boolean next():游標向下移動一行,判斷當前行是否是最后一行末尾(是否有數據);如果是,則返回false,如果不是則返回true。
?? ??? ?* getXxx(參數):獲取數據
?? ??? ??? ?* Xxx:代表數據類型? ?如:int getInt()、String getString()
?? ??? ??? ?* 參數:
?? ??? ??? ??? ?1. int:代表列的編號,從1開始,如: getString(1)
?? ??? ??? ??? ?2. String:代表列名稱,如: getDouble("balance")
??
package cn.itcast.jdbc;import java.sql.*;/*** 執行DDL語句*/ public class JDBCDemo6 {public static void main(String[] args) {Connection conn = null;Statement stmt = null;ResultSet rs = null;try {//1. 注冊驅動Class.forName("com.mysql.jdbc.Driver");//2.獲取連接對象conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");//3.定義sqlString sql = "select * from account";//4.獲取執行sql對象stmt = conn.createStatement();//5.執行sqlrs = stmt.executeQuery(sql);//6.處理結果//6.1 讓游標向下移動一行rs.next();//6.2 獲取數據int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {//7.釋放資源if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}} }JDBC各個類詳解_ResultSet_遍歷
4. ResultSet:結果集對象,封裝查詢結果
?? ??? ?* boolean next(): 游標向下移動一行,判斷當前行是否是最后一行末尾(是否有數據);如果是,則返回false;如果不是則返回true。
?? ??? ?* getXxx(參數):獲取數據
?? ??? ??? ?* Xxx:代表數據類型,如:int getInt(),String getString()
?? ??? ??? ?* 參數:
?? ??? ??? ??? ?1. int:代表列的編號,從1開始,如: getString(1)
?? ??? ??? ??? ?2. String:代表列名稱。如: getDouble("balance")
?? ??? ?
?? ??? ?* 注意:
?? ??? ??? ?* 使用步驟:
?? ??? ??? ??? ?1. 游標向下移動一行
?? ??? ??? ??? ?2. 判斷是否有數據
?? ??? ??? ??? ?3. 獲取數據
?? ??? ??? ? ? //6.1 循環判斷游標是否是最后一行末尾。
?? ? ? ? ? ? ? ?while(rs.next()){
?? ? ? ? ? ? ? ? ? ?//6.2 獲取數據
?? ? ? ? ? ? ? ? ? ?int id = rs.getInt(1);
?? ? ? ? ? ? ? ? ? ?String name = rs.getString("name");
?? ? ? ? ? ? ? ? ? ?double balance = rs.getDouble(3);
?? ? ? ? ? ? ? ? ? ?System.out.println(id + "---" + name + "---" + balance);
?? ? ? ? ? ? ? ?}
報錯的代碼:
package cn.itcast.jdbc;import java.sql.*;/*** 執行DDL語句*/ public class JDBCDemo6 {public static void main(String[] args) {Connection conn = null;Statement stmt = null;ResultSet rs = null;try {//1. 注冊驅動Class.forName("com.mysql.jdbc.Driver");//2.獲取連接對象conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");//3.定義sqlString sql = "select * from account";//4.獲取執行sql對象stmt = conn.createStatement();//5.執行sqlrs = stmt.executeQuery(sql);//6.處理結果//6.1 讓游標向下移動一行rs.next();//6.2 獲取數據int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);//6.1 讓游標向下移動一行rs.next();//6.2 獲取數據int id2 = rs.getInt(1);String name2 = rs.getString("name");double balance2 = rs.getDouble(3);System.out.println(id2 + "---" + name2 + "---" + balance2);//6.1 讓游標向下移動一行rs.next();//6.2 獲取數據int id3 = rs.getInt(1);String name3 = rs.getString("name");double balance3 = rs.getDouble(3);System.out.println(id3 + "---" + name3 + "---" + balance3);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {//7.釋放資源if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}} } package cn.itcast.jdbc;import java.sql.*;/*** 執行DDL語句*/ public class JDBCDemo7 {public static void main(String[] args) {Connection conn = null;Statement stmt = null;ResultSet rs = null;try {//1. 注冊驅動Class.forName("com.mysql.jdbc.Driver");//2.獲取連接對象conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");//3.定義sqlString sql = "select * from account";//4.獲取執行sql對象stmt = conn.createStatement();//5.執行sqlrs = stmt.executeQuery(sql);//6.處理結果//6.1 循環判斷游標是否是最后一行末尾。while (rs.next()) {//6.2 獲取數據int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);}/* //6.1 讓游標向下移動一行if(rs.next()){//判斷是否有數據//6.2 獲取數據int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);}//6.1 讓游標向下移動一行if(rs.next()){//判斷是否有數據//6.2 獲取數據int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);}//6.1 讓游標向下移動一行if(rs.next()){//判斷是否有數據//6.2 獲取數據int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);}//6.1 讓游標向下移動一行if(rs.next()){//判斷是否有數據//6.2 獲取數據int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);}*//* //6.1 讓游標向下移動一行rs.next();//6.2 獲取數據int id2 = rs.getInt(1);String name2 = rs.getString("name");double balance2 = rs.getDouble(3);System.out.println(id2 + "---" + name2 + "---" + balance2);//6.1 讓游標向下移動一行rs.next();//6.2 獲取數據int id3 = rs.getInt(1);String name3 = rs.getString("name");double balance3 = rs.getDouble(3);System.out.println(id3 + "---" + name3 + "---" + balance3);*/} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {//7.釋放資源if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}} }05?JDBC登錄案例練習
JDBC練習_select語句
4. ResultSet:結果集對象,封裝查詢結果
?? ??? ?* boolean next(): 游標向下移動一行,判斷當前行是否是最后一行末尾(是否有數據);如果是,則返回false;如果不是則返回true。
?? ??? ?* getXxx(參數):獲取數據
?? ??? ??? ?* Xxx:代表數據類型,如:int getInt(),String getString()
?? ??? ??? ?* 參數:
?? ??? ??? ??? ?1. int:代表列的編號,從1開始,如: getString(1)
?? ??? ??? ??? ?2. String:代表列名稱。如: getDouble("balance")
?? ??? ?
?? ??? ?* 注意:
?? ??? ??? ?* 使用步驟:
?? ??? ??? ??? ?1. 游標向下移動一行
?? ??? ??? ??? ?2. 判斷是否有數據
?? ??? ??? ??? ?3. 獲取數據
?? ??? ??? ? ? //6.1 循環判斷游標是否是最后一行末尾。
?? ? ? ? ? ? ? ?while(rs.next()){
?? ? ? ? ? ? ? ? ? ?//6.2 獲取數據
?? ? ? ? ? ? ? ? ? ?int id = rs.getInt(1);
?? ? ? ? ? ? ? ? ? ?String name = rs.getString("name");
?? ? ? ? ? ? ? ? ? ?double balance = rs.getDouble(3);
?? ? ? ? ? ? ? ? ? ?System.out.println(id + "---" + name + "---" + balance);
?? ? ? ? ? ? ? ?}
?? ??? ?* 練習:
?? ??? ??? ?* 定義一個方法,查詢emp表的數據將其封裝為對象,然后裝載集合,返回。
?? ??? ??? ??? ?1. 定義Emp類
?? ??? ??? ??? ?2. 定義方法 public List<Emp> findAll() {}
?? ??? ??? ??? ?3. 實現方法 select * from emp;
??
??
Emp.java //?封裝Emp表數據的JavaBean
package cn.itcast.domain;import java.util.Date;/*** 封裝Emp表數據的JavaBean*/ public class Emp {private int id;private String ename;private int job_id;private int mgr;private Date joindate;private double salary;private double bonus;private int dept_id;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getEname() {return ename;}public void setEname(String ename) {this.ename = ename;}public int getJob_id() {return job_id;}public void setJob_id(int job_id) {this.job_id = job_id;}public int getMgr() {return mgr;}public void setMgr(int mgr) {this.mgr = mgr;}public Date getJoindate() {return joindate;}public void setJoindate(Date joindate) {this.joindate = joindate;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public int getDept_id() {return dept_id;}public void setDept_id(int dept_id) {this.dept_id = dept_id;}public double getBonus() {return bonus;}public void setBonus(double bonus) {this.bonus = bonus;}@Overridepublic String toString() {return "Emp{" +"id=" + id +", ename='" + ename + '\'' +", job_id=" + job_id +", mgr=" + mgr +", joindate=" + joindate +", salary=" + salary +", bonus=" + bonus +", dept_id=" + dept_id +'}';} }JDBCDemo8.java
package cn.itcast.jdbc;import cn.itcast.domain.Emp; import cn.itcast.util.JDBCUtils;import java.sql.*; import java.util.ArrayList; import java.util.List;/*** * 定義一個方法,查詢emp表的數據將其封裝為對象,然后裝載集合,返回。*/ public class JDBCDemo8 {public static void main(String[] args) {List<Emp> list = new JDBCDemo8().findAll();System.out.println(list);System.out.println(list.size());for (Emp x : list) {System.out.println(x);}}/*** 查詢所有emp對象** @return*/public List<Emp> findAll() {Connection conn = null;Statement stmt = null;ResultSet rs = null;List<Emp> list = null;try {//1.注冊驅動Class.forName("com.mysql.jdbc.Driver");//2.獲取連接conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");//3.定義sqlString sql = "select * from emp";//4.獲取執行sql的對象stmt = conn.createStatement();//5.執行sqlrs = stmt.executeQuery(sql);//6.遍歷結果集,封裝對象,裝載集合Emp emp = null;list = new ArrayList<Emp>();while (rs.next()) {//獲取數據int id = rs.getInt("id");String ename = rs.getString("ename");int job_id = rs.getInt("job_id");int mgr = rs.getInt("mgr");Date joindate = rs.getDate("joindate");double salary = rs.getDouble("salary");double bonus = rs.getDouble("bonus");int dept_id = rs.getInt("dept_id");// 創建emp對象,并賦值emp = new Emp();emp.setId(id);emp.setEname(ename);emp.setJob_id(job_id);emp.setMgr(mgr);emp.setJoindate(joindate);emp.setSalary(salary);emp.setBonus(bonus);emp.setDept_id(dept_id);//裝載集合list.add(emp);}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}return list;}}JDBC工具類
抽取JDBC工具類 : JDBCUtils
* 目的:簡化書寫
* 分析:
?? ?1. 注冊驅動也抽取
?? ?2. 抽取一個方法獲取連接對象
?? ??? ?* 需求:不想傳遞參數(麻煩),還得保證工具類的通用性。
?? ??? ?* 解決:配置文件
?? ??? ??? ?jdbc.properties
?? ??? ??? ??? ?url=...
?? ??? ??? ??? ?user=...
?? ??? ??? ??? ?password=...
?? ?3. 抽取一個方法釋放資源
?? ??? ?* 代碼實現:...
??
Java19-day10【標準輸入輸出流、字節字符打印流、對象序列化-反序列化流、serialVersionUID&transient、Properties】
Properties介紹
- 是一個Map體系的集合類。
- Properties可以保存到流中或從流中加載。
- 屬性列表中的每個鍵及其對應的值都是一個字符串。
?
??
package cn.itcast.util;import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties;/*** JDBC工具類*/ public class JDBCUtils {private static String url;private static String user;private static String password;private static String driver;/*** 文件的讀取,只需要讀取一次即可拿到這些值。使用靜態代碼塊* 靜態代碼塊,隨著類的加載而執行(只會執行一次)*/static {//讀取資源文件,獲取值。try {//1. 創建Properties集合類。Properties pro = new Properties();//獲取src路徑下的文件的方式--->ClassLoader 類加載器:加載字節碼文件進內存、獲取src下資源文件的路徑//獲取ClassLoader要先獲取其對應的字節碼文件對象ClassLoader classLoader = JDBCUtils.class.getClassLoader();//以src為相對的根路徑 統一資源定位符URLURL res = classLoader.getResource("jdbc.properties"); // 傳文件名,獲取resource資源String path = res.getPath();// System.out.println(path);///D:/IdeaProjects/itcast/out/production/day04_jdbc/jdbc.properties//2. 加載文件// pro.load(new FileReader("D:\\IdeaProjects\\itcast\\day04_jdbc\\src\\jdbc.properties"));pro.load(new FileReader(path));//3. 獲取數據,賦值url = pro.getProperty("url");user = pro.getProperty("user");password = pro.getProperty("password");driver = pro.getProperty("driver");//4. 注冊驅動Class.forName(driver);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}/*** 獲取連接** @return 連接對象*/public static Connection getConnection() throws SQLException {return DriverManager.getConnection(url, user, password);}/*** 釋放資源** @param stmt* @param conn*/public static void close(Statement stmt, Connection conn) {if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}/*** 釋放資源** @param stmt* @param conn*/public static void close(ResultSet rs, Statement stmt, Connection conn) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}JDBC練習_登錄案例
* 練習:
?? ?* 需求:
?? ??? ?1. 通過鍵盤錄入用戶名和密碼
?? ??? ?2. 判斷用戶是否登錄成功
?? ??? ??? ?* select * from user where username = "" and password = "";
?? ??? ??? ?* 如果這個sql有查詢結果,則成功,反之,則失敗
?? ?* 步驟:
?? ??? ?1. 創建數據庫表 user
?? ??? ??? ?CREATE TABLE USER(
?? ??? ??? ??? ?id INT PRIMARY KEY AUTO_INCREMENT,
?? ??? ??? ??? ?username VARCHAR(32),
?? ??? ??? ??? ?PASSWORD VARCHAR(32)
?? ??? ??? ?);
?? ??? ??? ?INSERT INTO USER VALUES(NULL,'zhangsan','123');
?? ??? ??? ?INSERT INTO USER VALUES(NULL,'lisi','234');
?? ??? ?2. 代碼實現:...
package cn.itcast.jdbc;import cn.itcast.util.JDBCUtils;import java.sql.*; import java.util.Scanner;/*** 練習:* * 需求:* 1. 通過鍵盤錄入用戶名和密碼* 2. 判斷用戶是否登錄成功*/ public class JDBCDemo9 {public static void main(String[] args) {//1.鍵盤錄入,接受用戶名和密碼Scanner sc = new Scanner(System.in);System.out.println("請輸入用戶名:");String username = sc.nextLine();System.out.println("請輸入密碼:");String password = sc.nextLine();//2.調用方法 非靜態方法,需要創建對象來調用boolean flag = new JDBCDemo9().login(username, password);//3.判斷結果,輸出不同語句if (flag) {//登錄成功System.out.println("登錄成功!");} else {System.out.println("用戶名或密碼錯誤!");}}/*** 登錄方法*/public boolean login(String username, String password) {if (username == null || password == null) {return false;}//連接數據庫判斷是否登錄成功Connection conn = null;Statement stmt = null;ResultSet rs = null;//1.獲取連接try {conn = JDBCUtils.getConnection();//2.定義sqlString sql = "select * from user where username = '" + username + "' and password = '" + password + "' ";System.out.println(sql);//3.獲取執行sql的對象stmt = conn.createStatement();//4.執行查詢rs = stmt.executeQuery(sql);//5.判斷/* if(rs.next()){//如果有下一行,則返回truereturn true;}else{return false;}*/return rs.next();//如果有下一行,則返回true} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtils.close(rs, stmt, conn);}return false;}}06?PreparedStatement類詳解
JDBC各個類詳解_PreparedStatement
5. PreparedStatement:執行sql的對象
?? ??? ?1. SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接,會造成安全性問題。
?? ??? ??? ?1. 輸入用戶隨便,輸入密碼:a' or 'a' = 'a
?? ??? ??? ?2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a'?
?? ??? ?2. 解決sql注入問題:使用PreparedStatement對象來解決
?? ??? ?3. 預編譯的SQL:參數使用?作為占位符
?? ??? ?4. 步驟:
?? ??? ??? ?1. 導入驅動jar包 mysql-connector-java-5.1.37-bin.jar
?? ??? ??? ?2. 注冊驅動
?? ??? ??? ?3. 獲取數據庫連接對象 Connection
?? ??? ??? ?4. 定義sql
?? ??? ??? ??? ?* 注意:sql的參數使用?作為占位符, 如:select * from user where username = ? and password = ?;
?? ??? ??? ?5. 獲取執行sql語句的對象 PreparedStatement ?Connection.prepareStatement(String sql)?
?? ??? ??? ?6. 給?賦值:
?? ??? ??? ??? ?* 方法: setXxx(參數1,參數2)
?? ??? ??? ??? ??? ?* 參數1:?的位置編號 從1 開始
?? ??? ??? ??? ??? ?* 參數2:?的值
?? ??? ??? ?7. 執行sql,接受返回結果,不需要傳遞sql語句
?? ??? ??? ?8. 處理結果
?? ??? ??? ?9. 釋放資源
?? ??? ?5. 注意:后期都會使用PreparedStatement來完成增刪改查的所有操作
?? ??? ??? ?1. 可以防止SQL注入
?? ??? ??? ?2. 效率更高
??
登錄案例——解決sql注入問題
package cn.itcast.jdbc;import cn.itcast.util.JDBCUtils;import java.sql.*; import java.util.Scanner;/*** 練習:* * 需求:* 1. 通過鍵盤錄入用戶名和密碼* 2. 判斷用戶是否登錄成功*/ public class JDBCDemo9 {public static void main(String[] args) {//1.鍵盤錄入,接受用戶名和密碼Scanner sc = new Scanner(System.in);System.out.println("請輸入用戶名:");String username = sc.nextLine();System.out.println("請輸入密碼:");String password = sc.nextLine();//2.調用方法 非靜態方法,需要創建對象來調用boolean flag = new JDBCDemo9().login(username, password);//3.判斷結果,輸出不同語句if (flag) {//登錄成功System.out.println("登錄成功!");} else {System.out.println("用戶名或密碼錯誤!");}}/*** 登錄方法*/public boolean login(String username, String password) {if (username == null || password == null) {return false;}//連接數據庫判斷是否登錄成功Connection conn = null;Statement stmt = null;ResultSet rs = null;//1.獲取連接try {conn = JDBCUtils.getConnection();//2.定義sqlString sql = "select * from user where username = '" + username + "' and password = '" + password + "' ";System.out.println(sql);//3.獲取執行sql的對象stmt = conn.createStatement();//4.執行查詢rs = stmt.executeQuery(sql);//5.判斷/* if(rs.next()){//如果有下一行,則返回truereturn true;}else{return false;}*/return rs.next();//如果有下一行,則返回true} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtils.close(rs, stmt, conn);}return false;}/*** 登錄方法,使用PreparedStatement實現*/public boolean login2(String username, String password) {if (username == null || password == null) {return false;}//連接數據庫判斷是否登錄成功Connection conn = null;PreparedStatement pstmt = null;ResultSet rs = null;//1.獲取連接try {conn = JDBCUtils.getConnection();//2.定義sqlString sql = "select * from user where username = ? and password = ?";//3.獲取執行sql的對象pstmt = conn.prepareStatement(sql);//給?賦值pstmt.setString(1, username);pstmt.setString(2, password);//4.執行查詢,不需要傳遞sqlrs = pstmt.executeQuery();//5.判斷/* if(rs.next()){//如果有下一行,則返回truereturn true;}else{return false;}*/return rs.next();//如果有下一行,則返回true} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtils.close(rs, pstmt, conn);}return false;}}加油加油加油,寧死不破~~~
總結
以上是生活随笔為你收集整理的JDBC学习笔记02【ResultSet类详解、JDBC登录案例练习、PreparedStatement类详解】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JDBC学习笔记01【JDBC快速入门、
- 下一篇: 美国大学生数学建模竞赛 细节问题(23条