更新時(shí)間:2022-12-16 11:23:26 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1467次
Java連接SQL數(shù)據(jù)庫的代碼是什么?動(dòng)力節(jié)點(diǎn)小編來告訴大家。
package hello;
import java.sql.*;
public class test {
// MySQL 8.0 以下版本 - JDBC 驅(qū)動(dòng)名及數(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ū)動(dòng)名及數(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{
// 注冊(cè) JDBC 驅(qū)動(dòng)
Class.forName(JDBC_DRIVER);
// 打開鏈接
System.out.println("連接數(shù)據(jù)庫...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 執(zhí)行查詢
System.out.println(" 實(shí)例化Statement對(duì)象...");
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(", 站點(diǎn)名稱: " + name);
System.out.print(", 站點(diǎn) URL: " + url);
System.out.print("\n");
}
// 完成后關(guān)閉
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 處理 JDBC 錯(cuò)誤
se.printStackTrace();
}catch(Exception e){
// 處理 Class.forName 錯(cuò)誤
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!");
}
}
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)