標籤:
java定義了JDBC這一標準的介面和類,為程式員操作資料庫提供了統一的方式。
下載對應資料庫的jar包,添加到工程內。
JDBC的操作方式比較單一,由五個流程組成:
1.通過資料庫廠商提供的JDBC類庫向DriverManager註冊資料庫驅動
2.使用DriverManager提供的getConnection()方法串連到資料庫
3.通過資料庫的連線物件的createStatement方法建立SQL語句對象
4.執行SQL語句,並將結果集合返回到ResultSet中
5.使用while迴圈讀取結果
6.關閉資料庫資源
代碼舉例
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.sql.Statement; 6 7 public class TestJDBC 8 { 9 private final static String url = "jdbc:mysql://localhost:3306/test"; 10 11 private final static String user = ""; 12 13 private final static String password = ""; 14 15 public static void main(String[] args) 16 { 17 ResultSet rs = null; 18 Statement stmt = null; 19 20 // jdbc驅動載入 21 driverLoader(); 22 // 擷取資料庫連接 23 Connection conn = connectionGet(); 24 try 25 { 26 stmt = conn.createStatement(); 27 String sql = "select * from ljf"; 28 rs = stmt.executeQuery(sql); 29 while (rs.next()) 30 { 31 System.out.print(rs.getInt("id") + " "); 32 System.out.print(rs.getString("name") + " "); 33 } 34 } 35 catch (SQLException e) 36 { 37 System.out.println("資料操作錯誤"); 38 e.printStackTrace(); 39 } 40 finally 41 { 42 // 關閉資料庫 43 close(rs, stmt, conn); 44 } 45 } 46 47 private static void driverLoader() 48 { 49 try 50 { 51 Class.forName("com.mysql.jdbc.Driver"); // 載入mysql驅動 52 } 53 catch (ClassNotFoundException e) 54 { 55 System.out.println("驅動載入錯誤"); 56 e.printStackTrace(); 57 } 58 } 59 60 private static Connection connectionGet() 61 { 62 Connection conn = null; 63 try 64 { 65 conn = DriverManager.getConnection(url, user, password); 66 } 67 catch (SQLException e) 68 { 69 System.out.println("資料庫連結錯誤"); 70 e.printStackTrace(); 71 } 72 return conn; 73 } 74 75 private static void close(ResultSet rs, Statement stmt, Connection conn) 76 { 77 try 78 { 79 if (rs != null) 80 { 81 rs.close(); 82 rs = null; 83 } 84 if (stmt != null) 85 { 86 stmt.close(); 87 stmt = null; 88 } 89 if (conn != null) 90 { 91 conn.close(); 92 conn = null; 93 } 94 } 95 catch (Exception e) 96 { 97 System.out.println("資料庫關閉錯誤"); 98 e.printStackTrace(); 99 }100 }101 }
Java學習(十四):JDBC方式串連資料庫舉例