Java學習筆記之 JDBC連線MySQL的步驟》

2021-07-03 21:59:43 字數 1387 閱讀 3543

jdbc的六個固定步驟

1,註冊資料庫驅動:

·有多種方式可以註冊驅動

①drivemanager.regesiter(new com.mysql.jdbc.driver());   //需要導包,且會執行兩次

②class.forname("com.mysql.jdbc.driver");   //利用反射(推薦方式☆)

2,取得資料庫連線物件connection

connection conn = drivermanager.getconnection(url,user,pass);

url用於標識資料庫的位置,程式設計師通過url位址告訴jdbc程式連線哪個資料庫,url的寫法為:

連線資料庫自然而然要指明連線的是哪個主機哪個埠的哪個資料庫

3,建立sql物件

string sql = "select * from user where name = 'jack' ";  

對於preparedstatement物件 sql也可以使用佔位符  如sql = "select * from user where name = ?";  

有兩個方式

①statement物件 statement stmt = conn.createstatement();

②preparedstatement物件 preparedstatement pstmt = conn.preparedstatement(sql);  

pstmt.setstring(int parameterindex, string x);或者其他的set***x()   //動態新增sql引數(推薦的方式☆)

注:preperedstatement可以避免

sql注入

的問題。

statement會使資料庫頻繁編譯sql,可能造成資料庫緩衝區溢位。preparedstatement 可對sql進行預編譯,從而提高資料 庫的執行效率。

並且preperedstatement對於sql中的引數,允許使用佔位符的形式進行替換,簡化sql語句的編寫。

4,執行sql命令,並返回結果集

execute():用於向資料庫傳送任意sql語句

executequery() :只能向資料傳送select語句。

executeupdate():只能向資料庫傳送insert、update或delete語句

如pstmt.excute();

5,處理結果集

使用rs.next()返回的boolean值來進行處理

6,依次關閉結果集

在finally語句中判斷非空並關閉

JDBC 連線Mysql(筆記)

方法一 test public void testconnection1 throws exception 方法二 對方法一的迭代 在如下的程式中不出現第三方的api,使程式具有更好的可移植性 test public void testconnection2 throws exception 方式三...

java基礎之JDBC八 Druid連線池的使用

基本使用 druid連線池及簡單工具類的使用 public class test catch sqlexception e finally 簡單工具類 druid簡單工具類 public class druid utils 定義乙個變數 用來記錄資料庫連線池物件 private static dat...

JDBC學習筆記

size medium color red 本節jdbc的操作學習大致分為 color size size medium color red list 資料庫的裝載和連線 資料庫的增刪改查 資料庫的預編譯 資料庫的事務管理 list color size 下面直接上 了,還是 比較實在 以mysql...