jdbc远程连接MySQL

导入一个jar包
在这里插入图片描述
好像MySQL 8以上版本需要这个新的
但是我这里好像两种都可以,我的MySQL是5.7的
所以用了
jdbc远程连接MySQL_第1张图片
这个是我在其他网上查阅到的有不同的地方,但是我发现5.7的两种都可以,只要jar包对应就好。

// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
static final String URL = "jdbc:mysql://远程ip:3306/eecs";
 // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    static final String URL = "jdbc:mysql://远程ip:3306/eecs?useSSL=false&serverTimezone=UTC";

采取了8.0以下的那种。
然后

 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String URL = "jdbc:mysql://远程ip:3306/eecs";
 
    // 数据库的用户名与密码,需要根据自己的设置
    static final String NAME = "xxxxxx";
    static final String PWD = "xxxxxx";
 
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);
        
            // 连接数据库
            conn = DriverManager.getConnection(URL,NAME,PWD);
 
            System.out.println("连接数据库成功");
        
            // 执行查询
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * FROM tb_user";
            ResultSet rs = stmt.executeQuery(sql);
        
            while(rs.next()){
                int id  = rs.getInt("user_id");
                String name = rs.getString("user_name");
                String url = rs.getString("user_pwd");
    
                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", Name: " + name);
                System.out.print(", Pwd: " + url);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        }catch(Exception e1){
            e1.printStackTrace();
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
                if(conn!=null) conn.close();
            }catch(Exception e2){
            	e2.printStackTrace();
            }
        }
    }

你可能感兴趣的:(jdbc远程连接MySQL)