JDBC的配置及使用入門


JDBC本質上一套規范接口,建立java和數據庫的連接,從而對數據庫進行CRUD,下面以mysql數據庫為例,如圖:

JDBC的代碼實現:

 1 package JdbcUtil;
 2 
 3 ;
 4 
 5 /**
 6  * @author o_0sky
 7  * @date 2019/2/18 1:57
 8  */
 9 public class Standard {
10     //獲取連接
11     Connection con = null;
12     //創建statement對象
13     Statement statement = null;
14     ResultSet resultSet = null;
15     //注冊mysql驅動
16      try{Class.forName("com.mysql.jdbc.Driver");
17     //配置數據庫參數
18     String url = "jdbc:mysql://localhost:3306/test";
19     String username = "root";
20     String password = "root";
21     con=DriverManager.getConnection(url,username,password);
22     statement=con.createStatement();
23     //發送並執行sql
24     String sql = "select * from tb_user";
25     resultSet=statement.executeQuery(sql);
26     while(resultSet.next())
27     {
28         String name = resultSet.getString("name");
29         String age = resultSet.getString("age");
30         System.out.println(name);
31         System.out.println(age);
32     }}
33     catch(Exception e){
34          e.getStackTrace();
35     }
36     //釋放資源
37     finally{
38          if (resultSet!=null){
39              try {
40                  resultSet.close();
41              } catch (Exception e1) {
42                  e1.printStackTrace();
43              }
44          }
45          if (statement!=null){
46              try {
47                  statement.close();
48              } catch (Exception e1) {
49                  e1.printStackTrace();
50              }
51          }
52          if (con!=null){
53              try {
54                  con.close();
55              } catch (Exception e1) {
56                  e1.printStackTrace();
57              }
58          }
59     }
60 
61 
62 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM