是什么?
JDBC:Java Data Base Connectivity(java數據庫連接)
為什么用?
sun公司提供JDBC API接口,數據庫廠商來提供實現
我們需要用哪個數據庫就加載那個數據庫廠商提供的驅動包
怎么用?
- 需要先在數據庫中建立表
我的數據庫名為db_user,表名為t_user
2.在根目錄下創建lib文件夾,導入Mysql驅動程序,接着ctrl+shift+alt+s >> Modules >> 右側綠色加號 >> JARS >>選擇驅動程序
3.寫入以下程序:
步驟為:
- 加載數據庫驅動程序
- 獲取與數據庫連接的connection對象
- 獲取執行SQL語句的statement對象
- 執行SQL語句,拿到結果集
- 遍歷結果集,得到數據
- 關閉連接
package com.zhangwei.test; import java.sql.*; public class DBTest { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_user?useSSL=false", "root", "123456");
//黃色部分為 需要顯式禁用SSL設置usessl = false,或設置usessl =true提供服務器證書驗證信任庫。 statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM t_user"); while(resultSet.next()){ System.out.println(resultSet.getInt(1)); System.out.println(resultSet.getString(2)); System.out.println(resultSet.getString(3)); System.out.println(resultSet.getString(4)); } }catch (SQLException e){ e.printStackTrace(); }catch (ClassNotFoundException e){ e.printStackTrace(); }finally{ if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement != null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
運行結果:
需要知道的幾個對象
Connection對象:客戶端與數據庫的交互(DriverManager.getConnection()時返回此對象)
Statement對象:用於向數據庫發送Sql語句,實現數據庫的增刪改查(connection.createStatement()時返回此對象)
Resultset對象:代表SQL語句的執行結果(statement.executeQuery()時返回此對象)
轉載自:https://segmentfault.com/a/1190000013293202