Eclipse连接MySql数据库,两个问题的解决

在正确安装完MySQL和Eclipse各种配置好了后,尝试用网络上的代码连接数据库

网络代码如下:

import java.sql.*;
public class TestJDBC {
	  public static void main(String args[]) {
	    try {
	      Class.forName("com.mysql.jdbc.Driver");     //加载MYSQL JDBC驱动程序   
	      //Class.forName("org.gjt.mm.mysql.Driver");
	     System.out.println("Success loading Mysql Driver!");
	    }
	    catch (Exception e) {
	      System.out.print("Error loading Mysql Driver!");
	      e.printStackTrace();
	    }
	    try {
	      Connection connect = DriverManager.getConnection(
	          "jdbc:mysql://localhost:3306/hello","root","123456");
	           //连接URL为   jdbc:mysql//服务器地址/数据库名  ,后面的2个参数分别是登陆用户名和密码
	 
	      System.out.println("Success connect Mysql server!");
	      Statement stmt = connect.createStatement();
	      ResultSet rs = stmt.executeQuery("select * from user");
	                                                              //user 为你表的名称
	while (rs.next()) {
	        System.out.println(rs.getString("name"));            //name为表中的成员的名称
	      }
	    }
	    catch (Exception e) {
	      System.out.print("get data error!");
	      e.printStackTrace();
	    }
	  }

}

报错内容如下

第一个:Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.

根据提示将"com.mysql.jdbc.Driver"改为"com.mysql.cj.jdbc.Driver"

第二个按照网络上的方法在url后面添加useSSL=false

兰儿,运行还是这样的

Eclipse连接MySql数据库,两个问题的解决_第1张图片

有网真好啊)又去搜索了一波

在url后面添加了serverTimezone=GMT,完整的代码如下

import java.sql.*;
public class TestJDBC {
	  public static void main(String args[]) {
	    try {
	      Class.forName("com.mysql.cj.jdbc.Driver");     //加载MYSQL JDBC驱动程序   
	      //Class.forName("org.gjt.mm.mysql.Driver");
	     System.out.println("Success loading Mysql Driver!");
	    }
	    catch (Exception e) {
	      System.out.print("Error loading Mysql Driver!");
	      e.printStackTrace();
	    }
	    try {
	      Connection connect = DriverManager.getConnection(
	          "jdbc:mysql://localhost:3306/hello?serverTimezone=GMT&useSSL=false","root","123456");
	           //连接URL为   jdbc:mysql//服务器地址/数据库名  ,后面的2个参数分别是登陆用户名和密码
	 
	      System.out.println("Success connect Mysql server!");
	      Statement stmt = connect.createStatement();
	      ResultSet rs = stmt.executeQuery("select * from users");
	                                                              //users 为你表的名称
	while (rs.next()) {
	        System.out.println(rs.getString("id"
	        		));            //id为表中的成员的名称
	      }
	    }
	    catch (Exception e) {
	      System.out.print("get data error!");
	      e.printStackTrace();
	    }
	  }

}

就连接成功啦!

Eclipse连接MySql数据库,两个问题的解决_第2张图片

你可能感兴趣的:(java)