JDBC初探之遇到的問題以及解決方法
阿新 • • 發佈:2019-01-01
初學Java,記錄一下第一次JDBC資料庫操作遇到的問題和解決方法,如有錯誤,還請大神們不吝指正~
程式非常簡單,讀取本地mysql資料庫 ( 本地安裝mysql資料庫可參考:https://blog.csdn.net/zuolixiangfisher/article/details/74000294 ) 中infouser表裡的共五條記錄,資料如下:
以下程式碼參考了網上其他同學的程式碼,詳見參考資料
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
public class MysqlDemo1 {
// JDBC 驅動名以及資料庫 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/db_test";
// 資料庫使用者名稱和密碼
static final String USER = "test";
static final String PASSWORD = "testyhl";
public static void main(String[] args) throws Exception{
Connection conn = null;
Statement stmt = null;
try{
// 註冊 JDBC 驅動
Class.forName(JDBC_DRIVER);
// 開啟連結
System.out.println("連線資料庫...");
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
// 執行查詢
System.out.println("例項化Statement物件...");
stmt = conn.createStatement();
String sql;
sql = "SELECT userid, age, gender, keywords, topics FROM infouser";
ResultSet rs = stmt.executeQuery(sql);
// 展開結果集資料
while(rs.next()){
String userid = rs.getString("userid");
int age = rs.getInt("age");
String gender = rs.getString("gender");
String keywords = rs.getString("keywords");
String topics = rs.getString("topics");
System.out.print("UserId: " + userid);
System.out.print(" Age: " + age);
System.out.print(" Gender: " + gender);
System.out.print(" Keywords: " + keywords);
System.out.print(" Topics: " + topics);
System.out.println();
}
// 完成後關閉
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){
// do nothing
}
try{
if(conn!=null) {
conn.close();
}
}catch (SQLException se){
se.printStackTrace();
}
System.out.println("Goodbye!");
}
}
}
1、第一次執行報錯
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
問題原因:沒有引入mysql-connector-java-x.x.x-bin.jar
解決方案:增加mysql-connector-java配置,在pom.xml檔案里加入以下程式碼,然後重新重新整理IDEA載入 Jar包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
修改完後,再次執行
2、第二次執行報錯
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.
The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Tue Dec 25 17:52:32 GMT+08:00 2018 WARN: Establishing SSL connection without server's identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'.
You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
這個報錯資訊裡其實包含了幾個問題
第一個小問題
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.
The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
問題原因: mysql-connector包使用了新的驅動
解決方法1:jdbc.driver的屬性值從com.mysql.jdbc.Driver換為com.mysql.cj.jdbc.Driver.
解決方法2:在程式碼中去掉Class.forName(driver);,因為驅動會自動載入。
第二個小問題
Tue Dec 25 17:52:32 GMT+08:00 2018 WARN: Establishing SSL connection without server's identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
問題原因:連線的URL中需要增加時區資訊
解決方法:增加serverTimezone屬性並設定時區值,測試UTC(世界標準時間)和GMT(格林威治時間)都可以。
static final String DB_URL = "jdbc:mysql://localhost:3306/db_test?serverTimezone=GMT";
完成上面兩步,程式已經可以正常輸出結果,如下:
連線資料庫...
Tue Dec 25 18:28:15 GMT+08:00 2018 WARN: Establishing SSL connection without server's identity verification is not recommended.According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'.You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
例項化Statement物件...
UserId: 101 Age: 10 Gender: 2 Keywords: 魯迅 Topics: 文學
UserId: 102 Age: 20 Gender: 1 Keywords: 牛頓 Topics: 科學
UserId: 103 Age: 23 Gender: 1 Keywords: 杜甫 Topics: 文學
UserId: 104 Age: 43 Gender: 2 Keywords: 喬峰 Topics: 小說
UserId: 105 Age: 29 Gender: 0 Keywords: 阿杜 Topics: 明星
Goodbye!
可以看到,還有一個WARN,為了程式健壯性以及消除強迫症,必須把這個WARN幹掉。
第三個小問題
問題原因:關於SSL連線的Warning
解決方法:再在URL後面新增一個屬性useSSL,並設定為false
static final String DB_URL = "jdbc:mysql://localhost:3306/db_test?serverTimezone=GMT"&useSSL=false;
再次執行,完美
連線資料庫...
例項化Statement物件...
UserId: 101 Age: 10 Gender: 2 Keywords: 魯迅 Topics: 文學
UserId: 102 Age: 20 Gender: 1 Keywords: 牛頓 Topics: 科學
UserId: 103 Age: 23 Gender: 1 Keywords: 杜甫 Topics: 文學
UserId: 104 Age: 43 Gender: 2 Keywords: 喬峰 Topics: 小說
UserId: 105 Age: 29 Gender: 0 Keywords: 阿杜 Topics: 明星
Goodbye!
總結一下
建立一個以JDBC連線資料庫的程式,包含7個步驟
- 載入JDBC驅動程式
- 提供JDBC連線的URL
- 建立資料庫的連線
- 建立一個Statement
- 執行SQL語句
- 處理結果
- 關閉JDBC物件
最後完整的程式碼如下:
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
public class MysqlDemo1 {
// JDBC 驅動名以及資料庫 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/db_test?serverTimezone=GMT&useSSL=false";
// 資料庫使用者名稱和密碼
static final String USER = "test";
static final String PASSWORD = "testyhl";
public static void main(String[] args) throws Exception{
Connection conn = null;
Statement stmt = null;
try{
// 註冊 JDBC 驅動
// Class.forName(JDBC_DRIVER);
// 開啟連結
System.out.println("連線資料庫...");
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
// 執行sql查詢
System.out.println("例項化Statement物件...");
stmt = conn.createStatement();
String sql;
sql = "SELECT userid, age, gender, keywords, topics FROM infouser";
ResultSet rs = stmt.executeQuery(sql);
// 展開結果集資料
while(rs.next()){
String userid = rs.getString("userid");
int age = rs.getInt("age");
String gender = rs.getString("gender");
String keywords = rs.getString("keywords");
String topics = rs.getString("topics");
System.out.print("UserId: " + userid);
System.out.print(" Age: " + age);
System.out.print(" Gender: " + gender);
System.out.print(" Keywords: " + keywords);
System.out.print(" Topics: " + topics);
System.out.println();
}
// 完成後關閉
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){
// do nothing
}
try{
if(conn!=null) {
conn.close();
}
}catch (SQLException se){
se.printStackTrace();
}
System.out.println("Goodbye!");
}
}
}
參考資料:
[1] http://www.runoob.com/java/java-mysql-connect.html
[2] https://yq.aliyun.com/articles/614458
[3] https://blog.csdn.net/booloot/article/details/76223004
[4] http://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html