在Eclipse中使用MySQL遇到了點小問題
如果對Eclipse中配置MySql還有疑問的可以參考一下這篇博客:https://blog.csdn.net/qq_38247544/article/details/80419692
參考菜鳥上的例子的代碼如下:
當然,這是修改后沒問題后的代碼
1 package mysqltest; 2 3 import java.sql.*; 4 5 public class Mysql { 6 // jdbc驅動名以及數據庫URL 7 // static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; 8 static final String DB_URL = "jdbc:mysql://localhost:3306/javamysql" + "?serverTimezone=GMT%2B8"; 9 10 // 數據庫的用戶名與密碼,需要根據自己的設置 11 static final String USER = "root"; 12 static final String PASS = "root"; 13 14 public static void main(String[] args) { 15 Connection conn = null; 16 Statement stmt = null; 17 try { 18 // 注冊JDBC驅動 19 Class.forName("com.mysql.jdbc.Driver"); 20 21 // 打開鏈接 22 System.out.println("連接到數據庫……"); 23 conn = DriverManager.getConnection(DB_URL, USER, PASS); 24 25 // 執行查詢 26 System.out.println("實例化statement對象……"); 27 stmt = conn.createStatement(); 28 String sql; 29 sql = "SELECT id, name, url FROM websites"; 30 ResultSet rs = stmt.executeQuery(sql); 31 32 // 展開結果集數據庫 33 while (rs.next()) { 34 // 通過字段檢索 35 int id = rs.getInt("id"); 36 String name = rs.getString("name"); 37 String url = rs.getString("url"); 38 39 // 輸出數據 40 System.out.print("ID:" + id); 41 System.out.print(",站點名:" + name); 42 System.out.println(",站點URL:" + url); 43 } 44 45 // 完成后關閉 46 rs.close(); 47 stmt.close(); 48 conn.close(); 49 } catch (SQLException se) { 50 // 處理 JDBC錯誤 51 se.printStackTrace(); 52 } catch (Exception e) { 53 // 處理Class.forname 錯誤 54 e.printStackTrace(); 55 } finally { 56 // 關閉資源 57 try { 58 if (stmt != null) 59 stmt.close(); 60 } catch (SQLException se2) { 61 } // 什么都不做 62 try { 63 if (conn != null) 64 conn.close(); 65 } catch (SQLException se) { 66 se.printStackTrace(); 67 } 68 } 69 System.out.println("Goodbye!"); 70 } 71 }
遇到的問題如下:
原來是因為使用最新的驅動包中`com.mysql.jdbc.Driver'類已經過時,新的`com.mysql.cj.jdbc.Driver'通過SPI自動注冊,不再需要手動加載驅動類)
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.
但是后面還有一個如下的問題:
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.
找到了這篇博客
需要在數據庫 URL中設置serverTimezone屬性:(就是代碼第八行)
static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB" + "?serverTimezone=GMT%2B8"; 這里的 GMT%2B8 代表是東八區。(雖然不太明白為啥要加這個)
jdbc:mysql://localhost:3306/javamysql 端口號后面是你的數據庫
最后問題解決了,如果有遇到相同問題的小伙伴可以參考一下!