JDBC(Java DataBase Connectivity)
利用Java語言連接配接并通路資料庫的一門技術,besides,另外還可以通過cmd視窗或者navicat連接配接資料庫。
1.建立資料庫jt_db
2.建立工程并導入Java資料庫連接配接jar包(mysql-connector-java-5.1.32)
在Java基礎項目中建立一個lib目錄,Ctrl + V,建立自己的依賴庫lib,并把.jar檔案添加到依賴庫檔案清單中(這裡用的是Idea),如果是eclipse,選中.jar檔案,右鍵-->Build Path-->Add to Build Path,将.jar包引用到項目中。
JDBC_CURD
JDBC_CURD 連接配接資料庫步驟
1.注冊資料庫驅動
2.擷取資料庫連接配接
3.擷取傳輸器
4.發送sq語句到伺服器執行,并傳回執行結果
5.處理執行的結果
6.釋放資源
Class.forName("com.mysql.jdbc.Driver");
反射技術,利用類名加載相應.class檔案,将mysql驅動包中的“com.mysql.jdbc.Driver“”加載到記憶體中,Driver中的靜态代碼就會執行,Driver類的中的靜态代碼塊中有一行代碼是專門用于注冊驅動的,是以,這行代碼用于注冊驅動!
注冊驅動:将mysql驅動交給JDBC程式管理,,以便使用其中的功能
注意:在JDBC4.0以後的版本中,這一步可以省略,建議加上。
public class Test_Jdbc {
public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
//1.注冊資料庫驅動
Class.forName("com.mysql.jdbc.Driver");//反射
//2.擷取資料庫連接配接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jt_db?characterEncoding=utf-8", "root", "root");
//3.擷取傳輸器
stat = conn.createStatement();
//4.發送sql到伺服器執行并傳回執行結果
String sql = "select * from account";
rs = stat.executeQuery(sql);
//5.處理結果
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double monney = rs.getDouble("monney");
System.out.println(id + ":" + name + ":" + monney);
}
System.out.println("列印執行完成");
} catch (Exception e) {
e.printStackTrace();
} finally{
//6、釋放資源
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs = null;
}
}
if(stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
stat = null;
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
}
}
}