日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

JDBC-01-快速入门

發(fā)布時(shí)間:2024/7/19 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JDBC-01-快速入门 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

  • 01 JDBC快速入門
  • 02 JDBC各個(gè)類詳解
  • 03 JDBC之CRUD練習(xí)
  • 04 ResultSet類詳解
  • 05 JDBC登錄案例練習(xí)
    • 抽取JDBC工具類 : JDBCUtils
    • 練習(xí)
  • 06 PreparedStatement類詳解
  • 07 JDBC事務(wù)管理

目標(biāo)
1. JDBC基本概念
2. 快速入門
3. 對(duì)JDBC中各個(gè)接口和類詳解

01 JDBC快速入門

1. 概念:Java DataBase Connectivity Java 數(shù)據(jù)庫(kù)連接, Java語(yǔ)言操作數(shù)據(jù)庫(kù)* JDBC本質(zhì):其實(shí)是官方(sun公司)定義的一套操作所有關(guān)系型數(shù)據(jù)庫(kù)的規(guī)則,即接口。各個(gè)數(shù)據(jù)庫(kù)廠商去實(shí)現(xiàn)這套接口,提供數(shù)據(jù)庫(kù)驅(qū)動(dòng)jar包。我們可以使用這套接口(JDBC)編程,真正執(zhí)行的代碼是驅(qū)動(dòng)jar包中的實(shí)現(xiàn)類。2. 快速入門:* 步驟:1. 導(dǎo)入驅(qū)動(dòng)jar包 mysql-connector-java-5.1.37-bin.jar1.復(fù)制mysql-connector-java-5.1.37-bin.jar到項(xiàng)目的libs目錄下2.右鍵-->Add As Library2. 注冊(cè)驅(qū)動(dòng)3. 獲取數(shù)據(jù)庫(kù)連接對(duì)象 Connection4. 定義sql5. 獲取執(zhí)行sql語(yǔ)句的對(duì)象 Statement6. 執(zhí)行sql,接受返回結(jié)果7. 處理結(jié)果8. 釋放資源* 代碼實(shí)現(xiàn)://1. 導(dǎo)入驅(qū)動(dòng)jar包//2.注冊(cè)驅(qū)動(dòng)Class.forName("com.mysql.jdbc.Driver");//3.獲取數(shù)據(jù)庫(kù)連接對(duì)象Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");//4.定義sql語(yǔ)句String sql = "update account set balance = 500 where id = 1";//5.獲取執(zhí)行sql的對(duì)象 StatementStatement stmt = conn.createStatement();//6.執(zhí)行sqlint count = stmt.executeUpdate(sql);//7.處理結(jié)果System.out.println(count);//8.釋放資源stmt.close();conn.close();

02 JDBC各個(gè)類詳解

sql語(yǔ)句 execute、executeQuery和executeUpdate之間的區(qū)別:

  • DriverManager:驅(qū)動(dòng)管理對(duì)象
  • 注冊(cè)驅(qū)動(dòng)
  • 獲取數(shù)據(jù)庫(kù)連接
  • Connection:數(shù)據(jù)庫(kù)連接對(duì)象
  • Statement:執(zhí)行sql的對(duì)象
  • 1. DriverManager:驅(qū)動(dòng)管理對(duì)象* 功能:1. 注冊(cè)驅(qū)動(dòng):告訴程序該使用哪一個(gè)數(shù)據(jù)庫(kù)驅(qū)動(dòng)jarstatic void registerDriver(Driver driver) :注冊(cè)與給定的驅(qū)動(dòng)程序 DriverManager 。 寫代碼使用: Class.forName("com.mysql.jdbc.Driver");通過查看源碼發(fā)現(xiàn):在com.mysql.jdbc.Driver類中存在靜態(tài)代碼塊static {try {java.sql.DriverManager.registerDriver(new Driver());} catch (SQLException E) {throw new RuntimeException("Can't register driver!");}}注意:mysql5之后的驅(qū)動(dòng)jar包可以省略注冊(cè)驅(qū)動(dòng)的步驟。2. 獲取數(shù)據(jù)庫(kù)連接:* 方法:static Connection getConnection(String url, String user, String password) * 參數(shù):* url:指定連接的路徑* 語(yǔ)法:jdbc:mysql://ip地址(域名):端口號(hào)/數(shù)據(jù)庫(kù)名稱* 例子:jdbc:mysql://localhost:3306/db3* 細(xì)節(jié):如果連接的是本機(jī)mysql服務(wù)器,并且mysql服務(wù)默認(rèn)端口是3306,則url可以簡(jiǎn)寫為:jdbc:mysql:///數(shù)據(jù)庫(kù)名稱* user:用戶名* password:密碼 2. Connection:數(shù)據(jù)庫(kù)連接對(duì)象1. 功能:1. 獲取執(zhí)行sql 的對(duì)象* Statement createStatement()* PreparedStatement prepareStatement(String sql) 2. 管理事務(wù):* 開啟事務(wù):setAutoCommit(boolean autoCommit) :調(diào)用該方法設(shè)置參數(shù)為false,即開啟事務(wù)* 提交事務(wù):commit() * 回滾事務(wù):rollback() 3. Statement:執(zhí)行sql的對(duì)象1. 執(zhí)行sql1. boolean execute(String sql) :可以執(zhí)行任意的sql 了解 2. int executeUpdate(String sql) :執(zhí)行DML(insert、update、delete)語(yǔ)句、DDL(create,alter、drop)語(yǔ)句* 返回值:影響的行數(shù),可以通過這個(gè)影響的行數(shù)判斷DML語(yǔ)句是否執(zhí)行成功 返回值>0的則執(zhí)行成功,反之,則失敗。3. ResultSet executeQuery(String sql) :執(zhí)行DQL(select)語(yǔ)句 5. PreparedStatement:執(zhí)行sql的對(duì)象1. SQL注入問題:在拼接sql時(shí),有一些sql的特殊關(guān)鍵字參與字符串的拼接。會(huì)造成安全性問題1. 輸入用戶隨便,輸入密碼:a' or 'a' = 'a2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a' 2. 解決sql注入問題:使用PreparedStatement對(duì)象來(lái)解決3. 預(yù)編譯的SQL:參數(shù)使用?作為占位符4. 步驟:1. 導(dǎo)入驅(qū)動(dòng)jar包 mysql-connector-java-5.1.37-bin.jar2. 注冊(cè)驅(qū)動(dòng)3. 獲取數(shù)據(jù)庫(kù)連接對(duì)象 Connection4. 定義sql* 注意:sql的參數(shù)使用?作為占位符。 如:select * from user where username = ? and password = ?;5. 獲取執(zhí)行sql語(yǔ)句的對(duì)象 PreparedStatement Connection.prepareStatement(String sql) 6. 給?賦值:* 方法: setXxx(參數(shù)1,參數(shù)2)* 參數(shù)1:?的位置編號(hào) 從1 開始* 參數(shù)2:?的值7. 執(zhí)行sql,接受返回結(jié)果,不需要傳遞sql語(yǔ)句8. 處理結(jié)果9. 釋放資源5. 注意:后期都會(huì)使用PreparedStatement來(lái)完成增刪改查的所有操作1. 可以防止SQL注入2. 效率更高

    03 JDBC之CRUD練習(xí)

    java基礎(chǔ)總結(jié)(二十七)–Statement 和 PreparedStatement之間的關(guān)系和區(qū)別

    2. 練習(xí):1. account表 添加一條記錄2. account表 修改記錄3. account表 刪除一條記錄代碼:Statement stmt = null;Connection conn = null;try {//1. 注冊(cè)驅(qū)動(dòng)Class.forName("com.mysql.jdbc.Driver");//2. 定義sqlString sql = "insert into account values(null,'王五',3000)";//3.獲取Connection對(duì)象conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");//4.獲取執(zhí)行sql的對(duì)象 Statementstmt = conn.createStatement();//5.執(zhí)行sqlint count = stmt.executeUpdate(sql);//影響的行數(shù)//6.處理結(jié)果System.out.println(count);if(count > 0){System.out.println("添加成功!");}else{System.out.println("添加失敗!");}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally {//stmt.close();//7. 釋放資源//避免空指針異常if(stmt != null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if(conn != null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}

    04 ResultSet類詳解

    4. ResultSet:結(jié)果集對(duì)象,封裝查詢結(jié)果* boolean next(): 游標(biāo)向下移動(dòng)一行,判斷當(dāng)前行是否是最后一行末尾(是否有數(shù)據(jù)),如果是,則返回false,如果不是則返回true* getXxx(參數(shù)):獲取數(shù)據(jù)* Xxx:代表數(shù)據(jù)類型 如: int getInt() , String getString()* 參數(shù):1. int:代表列的編號(hào),1開始 如: getString(1)2. String:代表列名稱。 如: getDouble("balance")* 注意:* 使用步驟:1. 游標(biāo)向下移動(dòng)一行2. 判斷是否有數(shù)據(jù)3. 獲取數(shù)據(jù)//循環(huán)判斷游標(biāo)是否是最后一行末尾。while(rs.next()){//獲取數(shù)據(jù)//6.2 獲取數(shù)據(jù)int id = rs.getInt(1);String name = rs.getString("name");double balance = rs.getDouble(3);System.out.println(id + "---" + name + "---" + balance);}* 練習(xí):* 定義一個(gè)方法,查詢emp表的數(shù)據(jù)將其封裝為對(duì)象,然后裝載集合,返回。1. 定義Emp類2. 定義方法 public List<Emp> findAll(){}3. 實(shí)現(xiàn)方法 select * from emp;

    05 JDBC登錄案例練習(xí)

    抽取JDBC工具類 : JDBCUtils

    • 目的:簡(jiǎn)化書寫
    • 分析:
    • 注冊(cè)驅(qū)動(dòng)也抽取
    • 抽取一個(gè)方法獲取連接對(duì)象
      • 需求:不想傳遞參數(shù)(麻煩),還得保證工具類的通用性。
      • 解決:配置文件
        jdbc.properties
        url=
        user=
        password=
    • 抽取一個(gè)方法釋放資源
    * 代碼實(shí)現(xiàn):public class JDBCUtils {private static String url;private static String user;private static String password;private static String driver;/*** 文件的讀取,只需要讀取一次即可拿到這些值。使用靜態(tài)代碼塊*/static{//讀取資源文件,獲取值。try {//1. 創(chuàng)建Properties集合類。Properties pro = new Properties();//獲取src路徑下的文件的方式--->ClassLoader 類加載器ClassLoader classLoader = JDBCUtils.class.getClassLoader();URL res = classLoader.getResource("jdbc.properties");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. 獲取數(shù)據(jù),賦值url = pro.getProperty("url");user = pro.getProperty("user");password = pro.getProperty("password");driver = pro.getProperty("driver");//4. 注冊(cè)驅(qū)動(dòng)Class.forName(driver);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}/*** 獲取連接* @return 連接對(duì)象*/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();}}}}

    練習(xí)

    * 練習(xí):* 需求:1. 通過鍵盤錄入用戶名和密碼2. 判斷用戶是否登錄成功* select * from user where username = "" and password = "";* 如果這個(gè)sql有查詢結(jié)果,則成功,反之,則失敗* 步驟:1. 創(chuàng)建數(shù)據(jù)庫(kù)表 userCREATE 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. 代碼實(shí)現(xiàn):public class JDBCDemo9 {public static void main(String[] args) {//1.鍵盤錄入,接受用戶名和密碼Scanner sc = new Scanner(System.in);System.out.println("請(qǐng)輸入用戶名:");String username = sc.nextLine();System.out.println("請(qǐng)輸入密碼:");String password = sc.nextLine();//2.調(diào)用方法boolean flag = new JDBCDemo9().login(username, password);//3.判斷結(jié)果,輸出不同語(yǔ)句if(flag){//登錄成功System.out.println("登錄成功!");}else{System.out.println("用戶名或密碼錯(cuò)誤!");}}/*** 登錄方法*/public boolean login(String username ,String password){if(username == null || password == null){return false;}//連接數(shù)據(jù)庫(kù)判斷是否登錄成功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+"' ";//3.獲取執(zhí)行sql的對(duì)象stmt = conn.createStatement();//4.執(zhí)行查詢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類詳解

    PreparedStatement和動(dòng)態(tài)SQL

    什么是sql注入

    PreparedStatement:執(zhí)行sql的對(duì)象

  • SQL注入問題:在拼接sql時(shí),有一些sql的特殊關(guān)鍵字參與字符串的拼接。會(huì)造成安全性問題
    1. 輸入用戶隨便,輸入密碼:a’ or ‘a(chǎn)’ = 'a
    2. sql:select * from user where username = ‘fhdsjkf’ and password = ‘a(chǎn)’ or ‘a(chǎn)’ = ‘a(chǎn)’

  • 解決sql注入問題:使用PreparedStatement對(duì)象來(lái)解決

  • 預(yù)編譯的SQL:參數(shù)使用?作為占位符

  • 步驟:

  • 導(dǎo)入驅(qū)動(dòng)jar包 mysql-connector-java-5.1.37-bin.jar
  • 注冊(cè)驅(qū)動(dòng)
  • 獲取數(shù)據(jù)庫(kù)連接對(duì)象 Connection
  • 定義sql
    • 注意:sql的參數(shù)使用?作為占位符。 如:select * from user where username = ? and password = ?;
  • 獲取執(zhí)行sql語(yǔ)句的對(duì)象 PreparedStatement Connection.prepareStatement(String sql)
  • 給?賦值:
    • 方法: setXxx(參數(shù)1,參數(shù)2)
      • 參數(shù)1:?的位置編號(hào) 從1 開始
      • 參數(shù)2:?的值
  • 執(zhí)行sql,接受返回結(jié)果,不需要傳遞sql語(yǔ)句
  • 處理結(jié)果
  • 釋放資源
  • 注意:后期都會(huì)使用PreparedStatement來(lái)完成增刪改查的所有操作

  • 可以防止SQL注入
  • 效率更高
  • 07 JDBC事務(wù)管理

  • 事務(wù):一個(gè)包含多個(gè)步驟的業(yè)務(wù)操作。如果這個(gè)業(yè)務(wù)操作被事務(wù)管理,則這多個(gè)步驟要么同時(shí)成功,要么同時(shí)失敗。
  • 操作:
  • 開啟事務(wù)
  • 提交事務(wù)
  • 回滾事務(wù)
  • 使用Connection對(duì)象來(lái)管理事務(wù)
    • 開啟事務(wù):setAutoCommit(boolean autoCommit) :調(diào)用該方法設(shè)置參數(shù)為false,即開啟事務(wù)
      • 在執(zhí)行sql之前開啟事務(wù)
    • 提交事務(wù):commit()
      • 當(dāng)所有sql都執(zhí)行完提交事務(wù)
    • 回滾事務(wù):rollback()
      • 在catch中回滾事務(wù)
  • 4. 代碼:public class JDBCDemo10 {public static void main(String[] args) {Connection conn = null;PreparedStatement pstmt1 = null;PreparedStatement pstmt2 = null;try {//1.獲取連接conn = JDBCUtils.getConnection();//開啟事務(wù)conn.setAutoCommit(false);//2.定義sql//2.1 張三 - 500String sql1 = "update account set balance = balance - ? where id = ?";//2.2 李四 + 500String sql2 = "update account set balance = balance + ? where id = ?";//3.獲取執(zhí)行sql對(duì)象pstmt1 = conn.prepareStatement(sql1);pstmt2 = conn.prepareStatement(sql2);//4. 設(shè)置參數(shù)pstmt1.setDouble(1,500);pstmt1.setInt(2,1);pstmt2.setDouble(1,500);pstmt2.setInt(2,2);//5.執(zhí)行sqlpstmt1.executeUpdate();// 手動(dòng)制造異常int i = 3/0;pstmt2.executeUpdate();//提交事務(wù)conn.commit();} catch (Exception e) {//事務(wù)回滾try {if(conn != null) {conn.rollback();}} catch (SQLException e1) {e1.printStackTrace();}e.printStackTrace();}finally {JDBCUtils.close(pstmt1,conn);JDBCUtils.close(pstmt2,null);}}}

    i = 3/0;

    pstmt2.executeUpdate();//提交事務(wù)conn.commit();} catch (Exception e) {//事務(wù)回滾try {if(conn != null) {conn.rollback();}} catch (SQLException e1) {e1.printStackTrace();}e.printStackTrace();}finally {JDBCUtils.close(pstmt1,conn);JDBCUtils.close(pstmt2,null);}

    }

    }

    總結(jié)

    以上是生活随笔為你收集整理的JDBC-01-快速入门的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。