用idea+maven实现JDBC

注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注

pom.xml的配置:


        
            junit
            junit
            4.12
            test
        
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class QueryAll {
    public static void main(String[] args){
        Connection conn= null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //Class.forName("com.mysql.jdbc.Driver");
            String url ="jdbc:mysql://localhost/sunnie?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true";
            String username="root";
            String password="password";
            conn = DriverManager.getConnection(url,username,password);
            stmt = conn.createStatement();
            String sql = "select * from user";
            rs = stmt.executeQuery(sql);
            while(rs.next()) {
                System.out.println("用户名:" + rs.getString(2)+" 密码:"+ rs.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs!=null)
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            if (stmt!=null)
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            if (conn!=null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}

注意的问题:

(1)新版本的mysql里面要指明serverTimezone和是否进行SSL连接。

serverTimezone=UTC&useSSL=true

否则就会出现警告或者报错。

java.sql.SQLException: The server timezone value 'UTC' is unrecognized or represents more than one timezone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc timezone value if you want to utilize timezone support.
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.

(2)新版本mysql已经不再需要手动加载驱动,即不用写下面这行

Class.forName("com.mysql.jdbc.Driver");

写了反而会出警告

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.

你可能感兴趣的:(mysql)