最近在做一些java web整合時使用的最新版Mysql8.0.3,發現Mysql連接中的幾個問題,總結如下:
package db;//自定義包名 import java.sql.*; public class test1 { public static void main(String[] args) { // TODO Auto-generated method stub String user="root"; String password="123456"; String url="jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";//mydb為Mysql數據庫中創建的數據庫實例名 String driver="com.mysql.cj.jdbc.Driver"; String tableName="studinfo";//studinfo為數據庫mydb中的表名 String sqlstr; Connection con=null; Statement stmt=null; ResultSet rs=null; try { Class.forName(driver); con=DriverManager.getConnection(url, user, password); stmt=con.createStatement(); sqlstr="insert into "+tableName+ " value('1111','honey',21)";//into的后面和value前面一定要添加一個空格;value后面與左括號之間有無空格無所謂。 stmt.executeUpdate(sqlstr); sqlstr="select * from "+ tableName; rs=stmt.executeQuery(sqlstr); ResultSetMetaData rsmd=rs.getMetaData(); int j=0; j=rsmd.getColumnCount(); for(int k=0;k<j;k++) { System.out.print(rsmd.getColumnName(k+1)); System.out.print("\t"); } System.out.println(); while(rs.next()) { for(int i=0;i<j;i++) { System.out.print(rs.getString(i+1)); System.out.print("\t"); } System.out.println(); } } catch(ClassNotFoundException e1) { System.out.print("數據庫驅動不存在!"); System.out.print(e1.toString()); } catch(SQLException e2) { System.out.print("數據庫存在異常!"); System.out.print(e2.toString()); } finally { try { if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(con!=null) con.close(); } catch(SQLException e) { System.out.print(e.toString()); } } } }
常見錯誤提示1:
以上配置中,url中如果driver沒有添加cj,則會在連接的時候出現以下錯誤提示:
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.
解決辦法:根據提示,很顯然這種driver配置方式在此版本中已經被廢棄,因此需要將driverClass配置為:com.mysql.cj.jdbc.Driver。
常見錯誤提示2:
以上配置中,url中如果沒有設置useSSL=false,則會在連接的時候出現以下錯誤提示:
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.
解決辦法:在連接字符串中添加?useSSL=false
常見錯誤提示3:
以上配置中,url中如果沒有設置serverTimezone=UTC,則會在連接的時候出現以下錯誤提示:
The server time zone value '???ú±ê×??±??' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the
serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
解決辦法:在連接字符串中添加&serverTimezone=UTC
常見錯誤提示4:
錯誤提示:對實體 "serverTimezone" 的引用必須以 ';' 分隔符結尾。
解決辦法:在 xml 中 &符號是作為實體字符形式存在的。故需要在連接字符串中的將ServerTime前面的&符號修改為&,參見上面的代碼。