[TOC] 1.JDBC入門(mén)1.1.什么是JDBCJDBC從物理結(jié)構(gòu)上來(lái)說(shuō)就是java語(yǔ)言訪問(wèn)數(shù)據(jù)庫(kù)的一套接口集合,,本質(zhì)上是java語(yǔ)言根數(shù)據(jù)庫(kù)之間的協(xié)議,。JDBC提供一組類和接口,通過(guò)使用JDBC,,開(kāi)發(fā)人員可以使用java代碼發(fā)送sql語(yǔ)句,,來(lái)操作數(shù)據(jù)庫(kù) 1.2.使用JDBC發(fā)送SQL的前提登錄數(shù)據(jù)庫(kù)服務(wù)器(連接數(shù)據(jù)庫(kù)服務(wù)器)需要有以下幾項(xiàng):
1.3.JDBC接口的核心APIJDBC的接口主要來(lái)源于舊版的java.sql.和新版的javax.sql.
DriveManager類:驅(qū)動(dòng)管理器類,,用于管理所有注冊(cè)的驅(qū)動(dòng)程序
Connection接口:表示java程序和數(shù)據(jù)庫(kù)的連接對(duì)象。
Statement接口:用于執(zhí)行靜態(tài)sql語(yǔ)句
PreparedStatement接口:用于執(zhí)行預(yù)編譯sql語(yǔ)句,,是Statement的子接口
CallableStatement接口:用于執(zhí)行存儲(chǔ)過(guò)程sql語(yǔ)句,,是PreparedStatement的子接口
ResultSet接口:用于執(zhí)行存儲(chǔ)過(guò)程的sql語(yǔ)句
對(duì)ResultSet結(jié)果獲取數(shù)據(jù)的基本思想是:先指定行,,然后獲取該行上字段的值 ResultSet用于代表sql語(yǔ)句查詢的結(jié)果,對(duì)結(jié)果進(jìn)行封裝,,并使用游標(biāo)來(lái)獲取數(shù)據(jù),,在初始的時(shí)候,游標(biāo)在第一行之前 ,,調(diào)用ResultSet.next()方法,,可以使游標(biāo)指向具體的數(shù)據(jù)行,每調(diào)用一次向下調(diào)用一行,,調(diào)用該方法獲取該行的數(shù)據(jù),。 ResultSet是用于封裝結(jié)果的,,所以提供的主要是get方法,當(dāng)使用next()方法指定到一行的時(shí)候,,可以使用以下兩種方式來(lái)獲取指定行的字段值:
常用的幾個(gè)類型: ResultSet還提供了對(duì)結(jié)果集進(jìn)行定位行的方法:
2.使用Statement執(zhí)行SQL語(yǔ)句當(dāng)書(shū)庫(kù)已經(jīng)連接并準(zhǔn)備好sql語(yǔ)句之后,,就要將這個(gè)語(yǔ)句在數(shù)據(jù)庫(kù)中執(zhí)行,這個(gè)使用使用Statement對(duì)象,,該對(duì)象主要提供兩種方法,,一種是
使用executeUpdate插入,修改,,刪除代碼示例: /** * 測(cè)試Statement接口 */public class StatementDemo { private String url = 'jdbc:mysql://localhost:3306/db'; private String user = 'root'; private String password = 'root'; /** *1.創(chuàng)建表 */ @Test public void TestCteate(){ Connection connection=null; Statement statement=null; try { //1.驅(qū)動(dòng)注冊(cè)程序 Class.forName('com.mysql.jdbc.Driver'); //2.獲取連接對(duì)象 connection = DriverManager.getConnection(url,user,password); //3.創(chuàng)建Statement對(duì)象 statement=connection.createStatement(); //4.準(zhǔn)備sql String sql = 'CREATE TABLE student (id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2));'; //5.發(fā)送sql語(yǔ)句,,執(zhí)行sql語(yǔ)句,并返回結(jié)果被影響的行數(shù) int count = statement.executeUpdate(sql); //6.輸出 System.out.println('影響了'+count+'行,!'); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { //7.關(guān)閉連接(關(guān)閉順序:后開(kāi)發(fā)先關(guān)閉) if (statement!=null) try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } if (connection!=null) try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 插入數(shù)據(jù) * 修改數(shù)據(jù) * 刪除數(shù)據(jù) */ @Test public void TestInsert(){ Connection connection=null; Statement statement=null; try { //1.驅(qū)動(dòng)注冊(cè)程序 Class.forName('com.mysql.jdbc.Driver'); //2.獲取連接對(duì)象 connection = DriverManager.getConnection(url,user,password); //3.創(chuàng)建Statement對(duì)象 statement=connection.createStatement(); //4.準(zhǔn)備sql //其他的修改,,刪除,只需要更改這里的sql即可 //插入// String sql = 'INSERT INTO student(NAME,gender) VALUES ('張梅','女');'; //修改// String sql = 'UPDATE student SET NAME='張三' WHERE id=2'; //刪除 String sql = 'DELETE FROM student WHERE id=2'; //5.發(fā)送sql語(yǔ)句,,執(zhí)行sql語(yǔ)句,,并返回結(jié)果被影響的行數(shù) int count = statement.executeUpdate(sql); //6.輸出 System.out.println('影響了'+count+'行!'); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { //7.關(guān)閉連接(關(guān)閉順序:后開(kāi)發(fā)先關(guān)閉) if (statement!=null) try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } if (connection!=null) try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }} 使用executeQuery查詢數(shù)據(jù)代碼示例: /** * 查詢數(shù)據(jù) */ @Test public void TestFind(){ Connection connection=null; Statement statement=null; try { //1.驅(qū)動(dòng)注冊(cè)程序 Class.forName('com.mysql.jdbc.Driver'); //2.獲取連接對(duì)象 connection = DriverManager.getConnection(url,user,password); //3.創(chuàng)建Statement對(duì)象 statement=connection.createStatement(); //4.準(zhǔn)備sql String sql = 'SELECT * FROM student'; //5.發(fā)送sql語(yǔ)句,,執(zhí)行sql語(yǔ)句,,并返回查詢結(jié)果 ResultSet rs = statement.executeQuery(sql); //6.打印出數(shù)據(jù) //方法1:移動(dòng)光標(biāo): /* boolean flag = rs.next(); if(flag){ //取出列值 //方法1.1:以索引方式 int id = rs.getInt(1); String name = rs.getString(2); String gender = rs.getString(3); System.out.println(id+','+name+','+gender); //方法1.2:以列名稱 int id = rs.getInt('id'); String name = rs.getString('name'); String gender = rs.getString('gender'); System.out.println(id+','+name+','+gender); } */ //方法2:使用遍歷方法 //遍歷結(jié)果 while(rs.next()){ int id = rs.getInt('id'); String name = rs.getString('name'); String gender = rs.getString('gender'); System.out.println(id+','+name+','+gender); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { //7.關(guān)閉連接(關(guān)閉順序:后開(kāi)發(fā)先關(guān)閉) if (statement!=null) try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } if (connection!=null) try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } 注意: 3.使用PreparedStatement執(zhí)行SQL語(yǔ)句在Statement中,,可以發(fā)現(xiàn)在連接數(shù)據(jù)庫(kù)和釋放資源方面有代碼重復(fù)的部分,,這個(gè)時(shí)候可以把重復(fù)的部分抽取出來(lái),,現(xiàn)在把連接部分和關(guān)閉部分的代碼抽取放到j(luò)dbcUtil這個(gè)類中,,有連接方法和關(guān)閉方法,代碼示例如下: /** * jdbc工具類 * 數(shù)據(jù)庫(kù)連接和資源釋放 */public class jdbcUtil { private static String url='jdbc:mysql://localhost:3306/db'; private static String user='root'; private static String password='root'; /** * 靜態(tài)代碼塊(只加載一次) */ static { try { Class.forName('com.mysql.jdbc.Driver'); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println('驅(qū)動(dòng)程序注冊(cè)出錯(cuò)'); } } /** * 抽取獲取連接對(duì)象的方法 */ public static Connection getConnect(){ Connection conn = null; try { conn = DriverManager.getConnection(url,user,password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 釋放資源的方法 */ public static void close(Connection conn, Statement stmt){ if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn, Statement stmt, ResultSet rs){ if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } }} 重復(fù)的部分已經(jīng)抽取了,,現(xiàn)在使用抽取的部分來(lái)實(shí)現(xiàn)PreparedStatement接口的方法 /** * 插入數(shù)據(jù) */ @Test public void TestInsert(){ Connection conn = null; PreparedStatement pstmt = null; try { //1.獲取連接 conn = jdbcUtil.getConnect(); //2.準(zhǔn)備預(yù)編譯的sql String sql = 'INSERT INTO student(NAME,gender) VALUES(?,?)';//問(wèn)號(hào),?表示一個(gè)參數(shù)的占位符 //3.執(zhí)行編譯sql語(yǔ)句(語(yǔ)法檢查) pstmt = conn.prepareStatement(sql); //4.設(shè)置參數(shù) //參數(shù)的設(shè)置用兩個(gè)參數(shù),,第一個(gè)指定是第幾個(gè)問(wèn)號(hào),第二個(gè)是參數(shù)的值,,參數(shù)位置從1開(kāi)始 pstmt.setString(1, '李四'); pstmt.setString(2, '男'); //5.發(fā)送參數(shù),,執(zhí)行sql int count = pstmt.executeUpdate();//注意此處括號(hào)里不放sql System.out.println('影響了'+count+'行!'); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { jdbcUtil.close(conn,pstmt); } } 2.修改 /** * 更改數(shù)據(jù) */ @Test public void testUpdate() { Connection conn = null; PreparedStatement stmt = null; try { //1.獲取連接 conn = jdbcUtil.getConnect(); //2.準(zhǔn)備預(yù)編譯的sql String sql = 'UPDATE student SET NAME=? WHERE id=?'; //?表示一個(gè)參數(shù)的占位符 //3.執(zhí)行預(yù)編譯sql語(yǔ)句(檢查語(yǔ)法) stmt = conn.prepareStatement(sql); //4.設(shè)置參數(shù)值 /** * 參數(shù)一: 參數(shù)位置 從1開(kāi)始 */ stmt.setString(1, '王五'); stmt.setInt(2, 9); //5.發(fā)送參數(shù),,執(zhí)行sql int count = stmt.executeUpdate(); System.out.println('影響了'+count+'行'); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { jdbcUtil.close(conn, stmt); } } 3.刪除 /** * 刪除數(shù)據(jù) */ @Test public void testDelete() { Connection conn = null; PreparedStatement stmt = null; try { //1.獲取連接 conn = jdbcUtil.getConnect(); //2.準(zhǔn)備預(yù)編譯的sql String sql = 'DELETE FROM student WHERE id=?'; //?表示一個(gè)參數(shù)的占位符 //3.執(zhí)行預(yù)編譯sql語(yǔ)句(檢查語(yǔ)法) stmt = conn.prepareStatement(sql); //4.設(shè)置參數(shù)值 /** * 參數(shù)一: 參數(shù)位置 從1開(kāi)始 */ stmt.setInt(1, 9); //5.發(fā)送參數(shù),,執(zhí)行sql int count = stmt.executeUpdate(); System.out.println('影響了'+count+'行'); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { jdbcUtil.close(conn, stmt); } } 4.查詢 /** * 查詢數(shù)據(jù) */ @Test public void testQuery() { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { //1.獲取連接 conn = jdbcUtil.getConnect(); //2.準(zhǔn)備預(yù)編譯的sql String sql = 'SELECT * FROM student'; //3.預(yù)編譯 stmt = conn.prepareStatement(sql); //4.執(zhí)行sql rs = stmt.executeQuery(); //5.遍歷rs while(rs.next()){ int id = rs.getInt('id'); String name = rs.getString('name'); String gender = rs.getString('gender'); System.out.println(id+','+name+','+gender); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { //關(guān)閉資源 jdbcUtil.close(conn,stmt,rs); } } PreparedStatement 和 Statment 區(qū)別: 推薦使用PreparedStatement 4.CallableStatement執(zhí)行存儲(chǔ)過(guò)程CallableStatement是PreparedStatement的子類,,所以可以使用PreparedStatement的方法,即也可以使用編譯sql,,同時(shí)該類是用來(lái)執(zhí)行存儲(chǔ)過(guò)程的,,所以兩者之間是可以連在一起用的,。 # 帶有出入?yún)?shù)的存儲(chǔ)過(guò)程DELIMITER $CREATE PROCEDURE pro_findById(IN sid INT) BEGIN SELECT * FROM student WHERE id=sid; END $CALL pro_findById(4); 帶有輸出參數(shù)的存儲(chǔ)過(guò)程 # 帶有輸出參數(shù)的存儲(chǔ)過(guò)程DELIMITER $CREATE PROCEDURE pro_findById2(IN sid INT,OUT sname VARCHAR(20)) BEGIN SELECT name INTO sname FROM student WHERE id=sid; END $CALL pro_findById2(4,@name);SELECT @name; 使用jdbc分別調(diào)用以上兩種存儲(chǔ)過(guò)程 /** *使用CallableStatement調(diào)用存儲(chǔ)過(guò)程 */public class CallableStatementDemo { /** *調(diào)用帶有輸入?yún)?shù)的存儲(chǔ)過(guò)程 * CALL pro_findById(4); */ @Test public void testIn(){ Connection conn = null; CallableStatement cstmt = null; ResultSet rs = null; try { //1.獲取連接方法 conn = jdbcUtil.getConnect(); //2.準(zhǔn)備sql String sql = 'CALL pro_findById(?)';//可以執(zhí)行預(yù)編譯sql //3.預(yù)編譯 cstmt=conn.prepareCall(sql); //4.設(shè)置輸入?yún)?shù) cstmt.setInt(1,4); //5.發(fā)送參數(shù) rs = cstmt.executeQuery();//注意:所有調(diào)用存儲(chǔ)過(guò)程的sql語(yǔ)句都是使用executeQuery方法 //遍歷結(jié)果 while (rs.next()){ int id = rs.getInt('id'); String name = rs.getString('name'); String gender = rs.getString('gender'); System.out.println(id+','+name+','+gender); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { jdbcUtil.close(conn,cstmt,rs); } } /** * 執(zhí)行帶有輸出參數(shù)的存儲(chǔ)過(guò)程 * CALL pro_findById2(4,@NAME); */ @Test public void TestOut(){ Connection conn =null; CallableStatement cstmt = null; ResultSet rs = null; try { //1.獲取連接 conn = jdbcUtil.getConnect(); //2.準(zhǔn)備sql String sql = 'CALL pro_findById2(?,?)';//第一個(gè)?是輸入?yún)?shù),,第二個(gè)?是輸出參數(shù) //3.預(yù)編譯 cstmt = conn.prepareCall(sql); //4.設(shè)置輸入?yún)?shù) cstmt.setInt(1,4); //5.設(shè)置輸出參數(shù)(注冊(cè)輸出參數(shù)) /** * 參數(shù)一:參數(shù)位置 * 參數(shù)二:存儲(chǔ)過(guò)程中的輸出參數(shù)的jdbc類型 */ cstmt.registerOutParameter(2, Types.VARCHAR); //6.發(fā)送參數(shù),,執(zhí)行 cstmt.executeQuery();//結(jié)果不是返回到結(jié)果集中,,而是返回到輸出參數(shù)中 //7.得到輸出參數(shù)的值 /** * 索引值:預(yù)編譯sql中的輸出參數(shù)的位置 */ String result = cstmt.getString(2);//getXX方法專門(mén)用于獲取存儲(chǔ)過(guò)程中的輸出參數(shù) System.out.println(result); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { jdbcUtil.close(conn,cstmt,rs); } }} 5.類路徑的讀取和jdbcUtil的配置文件在jdbcUtil類中,我們把數(shù)據(jù)庫(kù),驅(qū)動(dòng),,用戶名,,密碼寫(xiě)死了,,以后想要修改就很麻煩,,這種情況,我們會(huì)把配置文件再次抽取出來(lái),,創(chuàng)建一個(gè)db.properties文件來(lái)保存一些配置文件。需要輸入信息,在這個(gè)文件里面配置就可以了 url=jdbc:mysql://localhost:3306/dbuser=rootpassword=123456driverClass=com.mysql.jdbc.Driver 然后,,在jdbcUtil類中調(diào)用: /** * jdbc工具類 * 數(shù)據(jù)庫(kù)連接和資源釋放 */public class jdbcUtil { private static String url=null; private static String user=null; private static String password=null; private static String driverClass=null; /** * 靜態(tài)代碼塊(只加載一次) */ static { try { //讀取db.properties Properties props = new Properties(); /** * 使用類路徑的讀取方法 */ /** * . :代表java命令運(yùn)行的目錄 * 在java項(xiàng)目下:點(diǎn) . java命令的運(yùn)行目錄從項(xiàng)目的根目錄開(kāi)始 * 在web項(xiàng)目下: 點(diǎn) . java命令的運(yùn)行目錄從tomcat/bin目錄開(kāi)始 * 使用點(diǎn).來(lái)指定目錄會(huì)產(chǎn)生在java 項(xiàng)目和javaweb項(xiàng)目中不適用的情況 */ /** * /:斜杠表示classpath的根目錄 * 在java項(xiàng)目下,,classpath的根目錄從bin目錄開(kāi)始 * 在web項(xiàng)目下,classpath的根目錄從WEB-INF/classes目錄開(kāi)始,。 * 而db.properties就在/目錄下 * 一般都是使用/來(lái)指定按文件名字 */ InputStream in = jdbcUtil.class.getResourceAsStream('/db.properties'); //加載文件 props.load(in); //讀取信息 url=props.getProperty('url'); user=props.getProperty('user'); password=props.getProperty('password'); driverClass=props.getProperty('driverClass'); Class.forName(driverClass); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println('驅(qū)動(dòng)程序注冊(cè)出錯(cuò)'); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 抽取獲取連接對(duì)象的方法 */ public static Connection getConnect(){ Connection conn = null; try { conn = DriverManager.getConnection(url,user,password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 釋放資源的方法 */ public static void close(Connection conn, Statement stmt){ if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn, Statement stmt, ResultSet rs){ if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } }} 其中比較重要的就是文件路徑的查找,,因?yàn)樵趈ava項(xiàng)目和javaweb項(xiàng)目中的文件路徑是不一樣的,這個(gè)時(shí)候就可以使用類路徑來(lái)查找,。java中也通常使用點(diǎn)和斜杠來(lái)指定路徑,,但是指定的路徑是不一樣的: 斜杠指定路徑: |
|