Java連接MySQL數據庫遇到的幾個小問題

Java連接數據庫出現的幾個小問題

現在是2018-12-19
使用的驅動包是mysql-connector-java-8.0.13.jar
MySQL是XAMPP中集成的MariaDB-10
由於利用Python爬蟲數據保存到數據庫中,在Java側需要調用。鑑於小項目不需要使用MyBatis或者hibernate之類的框架,所以利用原生jdbc進行操作。

    public static final String JDBC = "com.mysql.jdbc.Driver";
    public static final String DATABASE_NAME = "jdbc:mysql://localhost:3306/spiders";

    private static String username =  "root";
    private static String password =  "root";


    public static void main(String[] args){
        Connection conn = null;
        Statement  stat = null;

        try{
            Class.forName(JDBC);
            System.out.println("start");
            conn = DriverManager.getConnection(DATABASE_NAME, username, password);
            stat = conn.createStatement();
            String sql = "SELECT * FROM wanfang_data LIMIT 5";
            ResultSet set = stat.executeQuery(sql);

            while (set.next()){
                String title = set.getString("title");
                String summary = set.getString("summary");
                System.out.println("title: " + title + ";" + "\t" + "summary: " + summary);
            }

            set.close();
            stat.close();
            conn.close();
        }catch (SQLException e){
            e.printStackTrace();
        }catch (Exception e1){
            e1.printStackTrace();
        }
        finally {
            try{
                if (stat != null)
                    stat.close();
            }catch (SQLException e){

            }
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

以上的代碼是沒有辦法做正確運行的,主要是有兩個問題
1.驅動代碼包名發生的變動,網絡上大部分都是未更新的驅動包名,需要將包名更改爲"com.mysql.cj.jdbc.Driver";
2.SQLException,有一些亂碼和time zone之類的文字提示。

java.sql.SQLException: 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.

經過檢查,報錯是指本地和jar包時間不一致,需要在數據庫地址後添加serverTimezone=GMT,諸如本例就是變成 “jdbc:mysql://localhost:3306/spiders?serverTimezone=GMT”

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章