更新時間:2022-12-16 11:23:26 來源:動力節(jié)點 瀏覽1778次
Java連接SQL數(shù)據(jù)庫的代碼是什么?動力節(jié)點小編來告訴大家。
package hello;
import java.sql.*;
public class test {
// MySQL 8.0 以下版本 - JDBC 驅(qū)動名及數(shù)據(jù)庫 URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://192.166.195.86:3306/testdb";
// MySQL 8.0 以上版本 - JDBC 驅(qū)動名及數(shù)據(jù)庫 URL
//static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
//static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
// 數(shù)據(jù)庫的用戶名與密碼,需要根據(jù)自己的設(shè)置
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// 注冊 JDBC 驅(qū)動
Class.forName(JDBC_DRIVER);
// 打開鏈接
System.out.println("連接數(shù)據(jù)庫...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 執(zhí)行查詢
System.out.println(" 實例化Statement對象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// 展開結(jié)果集數(shù)據(jù)庫
while(rs.next()){
// 通過字段檢索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 輸出數(shù)據(jù)
System.out.print("ID: " + id);
System.out.print(", 站點名稱: " + name);
System.out.print(", 站點 URL: " + url);
System.out.print("\n");
}
// 完成后關(guān)閉
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 處理 JDBC 錯誤
se.printStackTrace();
}catch(Exception e){
// 處理 Class.forName 錯誤
e.printStackTrace();
}finally{
// 關(guān)閉資源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}