基本步驟
使用Java操作MySQL按步驟分為:
- 加載驅動
- 建立連接
- 創(chuàng)建Statement對象
- 傳遞SQL語句其监,并獲取執(zhí)行的結果集
- 遍歷結果集
- 關閉Statement對象
- 關閉連接
涉及知識:
- 類加載
- 集合
- 錯誤處理機制
可能遇到的情況:
情況1
運行提示:
Sat Dec 22 19:29:22 CST 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.
原因分析:
原本的驅動器不贊成 或者 是廢棄了卓鹿,自動換成了新的驅動器 com.mysql.cj.jdbc.Driver
咐吼。
解決方法:
將Class.forName()
中傳遞的值換成com.mysql.cj.jdbc.Driver
即可容劳。
情況2
運行提示:
Sat Dec 22 19:29:23 CST 2018 WARN: Caught while disconnecting...
EXCEPTION STACK TRACE:
** BEGIN NESTED EXCEPTION **
javax.net.ssl.SSLException
MESSAGE: closing inbound before receiving peer's close_notify
STACKTRACE:
javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:129)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:308)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:264)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:255)
at java.base/sun.security.ssl.SSLSocketImpl.shutdownInput(SSLSocketImpl.java:645)
at java.base/sun.security.ssl.SSLSocketImpl.shutdownInput(SSLSocketImpl.java:624)
at com.mysql.cj.mysqla.io.MysqlaProtocol.quit(MysqlaProtocol.java:1261)
at com.mysql.cj.mysqla.MysqlaSession.quit(MysqlaSession.java:314)
at com.mysql.cj.jdbc.ConnectionImpl.realClose(ConnectionImpl.java:1950)
at com.mysql.cj.jdbc.ConnectionImpl.close(ConnectionImpl.java:740)
at ConnectDemo.main(ConnectDemo.java:35)
** END NESTED EXCEPTION **
原因分析:
MySQL 8.0 以上版本巢寡,數(shù)據(jù)庫 URL 需要聲明是否使用 SSL 安全驗證及指定服務器上的時區(qū)
解決方案:
在數(shù)據(jù)庫地址上加上?useSSL=false&serverTimezone=UTC
风纠,如下:
static final String DB_URL = "jdbc:mysql://localhost:3306/empmgs?useSSL=false&serverTimezone=UTC";
例子
附上可以用的例子:
數(shù)據(jù)庫表的信息:
運行效果圖: