1.數據庫名為RUNOOB;
2.數據表名為websites,其中表里有三種數據- id,name,url。
3.語句如下:
mysql> create database RUNOOB;
Query OK, 1 row affected (0.00 sec)
mysql> use RUNOOB;
Database changed
mysql> create table websites(
-> id varchar(20),
-> name varchar(20),
-> url varchar(20)
-> );
Query OK, 0 rows affected (0.00 sec)
4.完整代碼示例:
import java.sql.*;
public class MySQLDemo {
// MySQL 8.0 以下版本 - JDBC 驅動名及數據庫 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false";
// MySQL 8.0 以上版本 - JDBC 驅動名及數據庫 URL
//static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
//static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&serverTimezone=UTC";
// 數據庫的用戶名與密碼,需要根據自己的設置
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// 注冊 JDBC 驅動
Class.forName(JDBC_DRIVER);
// 打開鏈接
System.out.println("連接數據庫...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 執行查詢
System.out.println(" 實例化Statement對象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// 展開結果集數據庫
while(rs.next()){
System.out.print("連接成功");
// 通過字段檢索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 輸出數據
System.out.print("ID: " + id);
System.out.print(", 站點名稱: " + name);
System.out.print(", 站點 URL: " + url);
System.out.print("\n");
}
// 完成后關閉
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 處理 JDBC 錯誤
se.printStackTrace();
}catch(Exception e){
// 處理 Class.forName 錯誤
e.printStackTrace();
}finally{
// 關閉資源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}