數據庫鏈接JDBC
阿新 • • 發佈:2017-09-01
todo .get exe boolean rate return timestamp 演示 tint 通過java_JDBC鏈接數據庫
jdbc:
java操作數據庫.jdbc是oracle公司指定的一套規範(一套接口)
驅動:jdbc的實現類.由數據庫廠商提供.
我們就可以通過一套規範操作不同的數據庫了(多態)
jdbc作用:
連接數據庫
發送sql語句
處理結果
步驟:
導入jar包:
- 註冊驅動
- 獲取鏈接
- 獲取執行者
- 執行sql語句
- 對結果進行操作
1//代碼演示: 2 //我們封裝一個工具類來提高代碼的擴展性 3 public class JDBCUtils { 4 private static final String url="jdbc:mysql://localhost:3306/test"; 5 private static final String username="root"; 6 private static final String password = "root"; 7 /** 8 * 註冊驅動 9 */10 static { 11 try { 12 Class.forName("com.mysql.jdbc.Driver"); 13 } catch (ClassNotFoundException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } 17 } 18 /**19 * 獲取鏈接 20 * @return 21 */ 22 public static Connection getConnention() { 23 Connection connection=null; 24 try { 25 connection = DriverManager.getConnection(url,username,password); 26 } catch (SQLException e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 return connection; 31 } 32 /** 33 * 通過可變參關閉連接 34 * @param objects 35 */ 36 public static void colse(Object ...objects) { 37 try { 38 if (objects!=null && objects.length>0) { 39 for(int i = 0;i<objects.length;i++) { 40 if(objects[i] instanceof Statement) { 41 ((Statement)objects[i]).close(); 42 }else if(objects[i] instanceof Connection) { 43 ((Connection)objects[i]).close(); 44 } 45 } 46 } 47 } catch (Exception e) { 48 e.printStackTrace(); 49 } 50 } 51 }
1 // 對工具類的使用 2 public class JDBCDemo { 3 public static void main(String[] args) { 4 //獲取鏈接 5 Connection connection = JDBCUtils.getConnention(); 6 //獲取執行者 7 ResultSet resultSet=null; 8 PreparedStatement pStatement=null; 9 10 //定義將要執行的sql語句 11 String sql = "select * from products where cno=?"; 12 //存放結果集對象 13 List<Product> list = new ArrayList<Product>(); 14 try { 15 //獲取語句執行者對象 16 pStatement = connection.prepareStatement(sql); 17 //設置參數 18 pStatement.setInt(1, 1); 19 //執行查詢操作 20 resultSet = pStatement.executeQuery(); 21 //遍歷結果集 22 while (resultSet.next()) { 23 Product product = new Product(); 24 product.setId(resultSet.getInt("pid")); 25 product.setName(resultSet.getString("pname")); 26 product.setPrice(resultSet.getInt("price")); 27 product.setNum(resultSet.getInt("pnum")); 28 product.setCno(resultSet.getInt("cno")); 29 product.setTimestamp(resultSet.getTimestamp("pdate")); 30 list.add(product); 31 } 32 } catch (SQLException e) { 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 }finally { 36 //關閉連接 37 JDBCUtils.colse(pStatement,connection); 38 } 39 for (Product product : list) { 40 System.out.println(product); 41 } 42 } 43 }
數據庫鏈接JDBC