JDBC是Java規定的訪問數據庫的API,目前主流的數據庫都支持JDBC。使用JDBC訪問不一樣的數據庫時須要安裝不一樣的驅動。java
JDBC定義了數據庫的連接,SQL語句的執行以及查詢結果集的遍歷等等。JDBC把這些操做定義爲接口,位於包java.sql下面,若是java.sql.Connection、java.sql.Statement、java.sql.ResultSet等。mysql
各個數據庫提供商在本身的JDBC驅動中實現了這些接口。sql
1.註冊驅動數據庫
2.獲取鏈接安全
3.獲取Statementoracle
4.執行SQL並返回結果集性能
5.遍歷結果集顯示數據url
6.釋放鏈接spa
package com.sean; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.mysql.jdbc.ResultSet; import com.mysql.jdbc.Statement; public class TestJDBC { public static final String PC_NAME = "pc_name"; public static final String IP = "ip"; public static void main(String[] args) { Statement stmt = null; Connection conn = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver");//首先註冊mysql驅動 String url = "jdbc:mysql://localhost/sean?user=root&password=root"; conn = DriverManager.getConnection(url);//鏈接mysql數據庫 String query = "select * from pc_ip_list"; stmt = (Statement) conn.createStatement();//獲取Statement rs = (ResultSet) stmt.executeQuery(query);//執行查詢語句 while (rs.next()) {//遍歷結果集 System.out.print(rs.getString(PC_NAME) + " "+ rs.getString(IP) + "\n"); } } catch (ClassNotFoundException e) { System.out.println("驅動程序未找到,請加入mysql.jdbc的驅動包。。。"); e.printStackTrace(); } catch (SQLException e) { System.out.println("執行SQL語句過程當中出現了錯誤。。。"); e.printStackTrace(); } finally {//釋放鏈接 try { //最後打開的最新關閉 if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
數據庫 鏈接URL code
MySQL jdbc:mysql://localhost:3306/db_name
Oracle jdbc:oracle:thin:@localhost:1521:db_name
DB2 jdbc:db2://localhost:6789/db
增刪改基本流程與上面的查詢同樣,只不過在執行sql語句的時候使用的是Statement的excuteUpdate方法,執行結果返回受影響的記錄條數。
String insertSql = "insert into sean values ('pc1', '127.0.0.1')"; String deleteSql = "delete from sean where name = 'pc1'"; stmt.executeUpdate(insertSql); stmt.executeUpdate(deleteSql);
上面的例子中增刪改查操做都是經過Statement對象實現的,使用Statement是最簡單的方式。除此以外還可以使用PreparedSattement,它繼承了Statement,最大區別是
PreparedStatement可使用參數,也就是(?)號。PreparedStatement可使用不完整的SQL語句,空缺的部分使用問號(?)代替,直到執行前設置進去。今後即可以免上面構造sql語句時所帶來的種種不方便(如加各類單引號'')。
package com.sean; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.mysql.jdbc.PreparedStatement; public class TestJDBC2 { public static void main(String args[]){ Connection conn = null; PreparedStatement pstmt = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/sean?user=root&password=root"); pstmt = (PreparedStatement) conn.prepareStatement("insert into sean values (?,?)");//獲取PreparedStatement pstmt.setString(1, "pstm1");//設置第一個?對應的值 pstmt.setString(2, "192.168.168.168");//設置第二個?對應的值 int count = pstmt.executeUpdate();//執行sql語句 if (count > 0){ System.out.print("excute success count = " + count); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null){ pstmt.close(); } if (conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
選擇PreparedStatement仍是Statement取決於你要怎麼使用它們。對於只執行一次的SQL語句選擇Statement是最好的. 相反,
若是SQL語句被屢次執行選用PreparedStatement是最好的。
PreparedStatement: 數據庫會對sql語句進行預編譯,下次執行相同的sql語句時,數據庫端不會再進行預編譯了,而直接用數據庫的緩衝區,提升數據訪問的效率(但儘可能採用使用?號的方式傳遞參數),若是sql語句只執行一次,之後再也不復用。 從安全性上來看,PreparedStatement是經過?來傳遞參數的,避免了拼sql而出現sql注入的問題,因此安全性較好。在開發中,推薦使用 PreparedStatement。
PreparedStatement的第一次執行消耗是很高的。它的性能體如今後面的重複執行。
package com.sean; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.mysql.jdbc.Statement; public class TestBatch1 { public static void main(String[] args) { Statement stmt = null; Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/sean?user=root&password=root"); stmt = (Statement) conn.createStatement(); for (int i = 0; i < 5; ++i){ String insertSql = "insert into sean values ('pc', '192.168.1.1')"; System.out.println(insertSql); stmt.addBatch(insertSql);//添加語句到batch } int[] result = stmt.executeBatch();//執行batch for (int i = 0; i < result.length; ++i){ System.out.println("result" + i + " = " + result[i]);//打印每一條sql語句執行的結果 } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally{ try { if (stmt != null){ stmt.close(); } if (conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
package com.sean; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.mysql.jdbc.PreparedStatement; public class TestBatch2 { public static void main(String args[]){ Connection conn = null; PreparedStatement pstmt = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/sean?user=root&password=root"); pstmt = (PreparedStatement) conn.prepareStatement("insert into sean values (?,?)");//獲取PreparedStatement for (int i = 0; i < 5; i++){ pstmt.setString(1, "batch2");//設置第一個?對應的值 pstmt.setString(2, "188.168.168.168");//設置第二個?對應的值 pstmt.addBatch();//添加到batch } int[] result = pstmt.executeBatch();//批量執行sql語句 for (int i = 0; i < result.length; ++i){ System.out.println("result" + i + " = " + result[i]);//打印每一條sql語句執行的結果 } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null){ pstmt.close(); } if (conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }