使用的是Java7新增的自動關閉資源的try語句,try后面緊跟"()",在括號里面可聲明、初始化一個或多個資源(那些資源必須在程序結束時,顯示關閉的),而try語句結束時會自動關閉這些資源。
為保證try語句可正常關閉資源,這些資源實現(xiàn)類必須實現(xiàn)AutoCloseable或Closeable接口,實現(xiàn)這兩個接口就必須實現(xiàn)close()方法;Java 7修改了大部分的類使得它們繼承了AutoCloseable或Closeable接口。Connection、Statement、ResultSet等接口都繼承了AutoCloseable接口,因此它們都可以被try語句關閉。
在main方法中實現(xiàn)以下代碼
Class.forName("com.mysql.jdbc.Driver");
try (
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306" + "/test", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from admin");
)
{
while (rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
}
運行之后,能夠獲取表中數(shù)據(jù),但出現(xiàn)警告
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.
不建議在沒有服務器身份驗證的情況下建立SSL連接。根據(jù)MySQL 5.5.45+、5.6.26+和5.7.6+的要求,如果沒有設置顯式選項,必須默認建立SSL連接,因為如果不使用SSL,那么verifyserver證書屬性將被設置為“false”。您需要通過設置useSSL=false來顯式地禁用SSL,或者設置useSSL=true,并為服務器證書驗證提供信任存儲。
解決方法是:
獲取數(shù)據(jù)庫連接時,在數(shù)據(jù)庫名后面添加參數(shù)"useSSL=true"或"useSSL=false"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306"+ "/test?useSSL=true", "root", "root123");