<代碼見文底>
jdbc的介紹就不寫了,隨便一搜就有。
一、導入包
大多數情況下使用import java.sql.*就行。
二、連接數據庫
首先註冊JDBC驅動程序:
Class.forName("com.mysql.jdbc.Driver");
然後連接數據庫:
Connection conn = null;
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/", //數據庫的url,這裏連的是數據庫根地址
"root", //用戶名
"123");//密碼
以上是針對MySQL8.0以上版本而言,如果你和我一樣用的是較新的版本,應該:
將"com.mysql.jdbc.Driver"改 爲"com.mysql.cj.jdbc.Driver"。
三、執行SQL語句
以創建新的數據庫,名爲 z_jdbc_test 爲例:
stmt = conn.createStatement();
String sql = "CREATE DATABASE z_jdbc_test";
stmt.executeUpdate(sql);
System.out.println("Database created successfully.");
刪庫、建表、刪表與此大體相同,不贅述。
如果是執行查詢語句,以Employees這個表爲例:
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
四、清理環境資源
rs.close();
stmt.close();
conn.close();
可能遇到的報錯
①運行ClassforName()時異常。首先檢查下里面的驅動程序名,再檢查下有項目沒有導入mysql驅動的jar包。
如果沒導入jar包,要去網上下載,並按https://jingyan.baidu.com/article/ca41422fc76c4a1eae99ed9f.html導入到項目中。
(假設你用的是eclipse)
②The Server time zone value 'XXXXX' (亂碼)這樣的報錯。
可以參考這篇博客:https://blog.csdn.net/Wei_NiZi/article/details/81509822,
簡單地說,在url後面加上?serverTimezone=UTC就可以了。使用較低版本的MySQL則沒有這個問題。
一點補充
url裏的”localhost“在其他教程裏可能是”127.0.0.1“,這兩者是等價的。它是回送地址,指本地機,用來測試使用,在Windows 中的別名即Localhost。而3306這個端口號是MySQL的默認端口,若使用其他DBMS就得改了。
代碼
import java.sql.*;//導入包
public class CreateDatabase {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/?serverTimezone=UTC";
static final String USER = "root";
static final String PASSWORD = "123";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//註冊JDBC驅動程序
Class.forName(JDBC_DRIVER);
//連接數據庫
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
//執行一個SQL語句
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE z_jdbc_test";
stmt.executeUpdate(sql);
System.out.println("Database created successfully.");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null) {
stmt.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}