基本步驟
使用Java操作MySQL按步驟分爲:
- 加載驅動
- 建立連接
- 創建Statement對象
- 傳遞SQL語句,並獲取執行的結果集
- 遍歷結果集
- 關閉Statement對象
- 關閉連接
實例
1.導入jar包
mysql-connector-java-8.0.16.jar
鏈接:https://pan.baidu.com/s/1jVDh3KbRgtNpXnjVudQPjg
提取碼:pxba
- 在項目中新建lib文件夾,並且複製粘貼jdbc包在文件夾中
- 右鍵單擊lib,選擇 Add as libary…
- 按 ok就行
2.上代碼
建表語句 :
CREATE TABLE `websites` (
`id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
`name` CHAR ( 20 ) NOT NULL DEFAULT '' COMMENT '站點名稱',
`url` VARCHAR ( 255 ) NOT NULL DEFAULT '',
`alexa` INT ( 11 ) NOT NULL DEFAULT '0' COMMENT 'Alexa 排名(全球排名)',
`country` CHAR ( 10 ) NOT NULL DEFAULT '' COMMENT '國家',
PRIMARY KEY ( `id` )
) ENGINE = INNODB AUTO_INCREMENT = 10 DEFAULT CHARSET = utf8;
INSERT INTO `websites`
VALUES
( '1', 'Google', 'https://www.google.com/', '1', 'USA' ),
( '2', '淘寶', 'https://www.taobao.com/', '9', 'CN' ),
( '3', '百度', 'https://www.baidu.com/', '6', 'CN' ),
( '4', '微博', 'http://weibo.com/', '16', 'CN' ),
( '5', 'Facebook', 'https://www.facebook.com/', '4', 'USA' ),
( '6', 'alexa', 'http://www.alexa.cn/', '86287', 'CN' );
COMMIT;#使用commit語句,提交事務
java代碼 :
package MySQL;
import java.sql.*;
public class a {
//加載驅動
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
// aaa 爲數據庫名
static final String DB_URL = "jdbc:mysql://localhost:3306/aaa";
// 數據庫的用戶名與密碼,需要根據自己的設置
static final String USER = "student";
static final String PASS = "aaaaaaaa";
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 * FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// 展開結果集數據庫
while(rs.next()){
// 通過字段檢索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
int alexa = rs.getInt("alexa");
String country = rs.getString("country");
// 輸出數據
System.out.print("ID: " + id);
System.out.print(", 站點名稱: " + name);
System.out.print(", 站點 URL: " + url);
System.out.print(", 站點 排名: " + alexa);
System.out.print(", 站點 國家: " + country);
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!");
}
}