目录

使用JDBC连接Mysql遇到的问题url中的数据库名字是什么

目录

使用JDBC连接Mysql遇到的问题:url中的数据库名字是什么?

以前学过一点编程,丢下好几年了,今天想重新捡起来。

在尝试使用Java的JDBC连接 Mysql数据库时,出现了一些问题,还有自己的一些疑惑,在此记录下来。

1.装载驱动的链接变了

以前的版本: Class.forName("com.mysql.jdbc.Driver") ;

现在这个链接过时了,需要更改成: Class.forName("com.mysql.cj.jdbc.Driver") ;

  1. 建立连接时URL中的数据库名字到底是什么?

url = “jdbc:mysql://localhost:3306/database_name” 中的 database_name到底是什么呢?

我看到有朋友问,这里就说一下我的经验。

在 Mysql中 使用语句: Show databases;

结果中出现的一些数据库就是database_name。在mysql中,使用数据前需要先执行语句: Use database_name ; Use语句中的那个数据库名字就是建立连接Url中的数据库名字。

https://i-blog.csdnimg.cn/blog_migrate/c129586ddbb558eddf8c83841fb642d9.png#pic_center

例如,我的 Url = “jdbc:mysql://localhost:3306/employees” 中那个 employees就是我的数据库名称。

核心代码如下:

Connection conn = null;

Statement stmt = null;

ResultSet rst = null;

String url = “jdbc:mysql://localhost:3306/employees?serverTimezone=UTC”;

String user = “username”;

String password = “password”;

try{

Class.forName(“com.mysql.cj.jdbc.Driver”);

conn = DriverManager.getConnection(url, user, password);

stmt = conn.createStatement();

String sql = “select emp_no, first_name, last_name from employees limit 0, 10;”;

rst = stmt.executeQuery(sql);

while(rst.next()){

int emp_no = rst.getInt(“emp_no”);

String first_name = rst.getString(“first_name”);

String last_name = rst.getString(“last_name”);

System.out.println(emp_no + “,” + first_name + “,” + last_name);

}

}catch(ClassNotFoundException e){

System.out.println(“没找到驱动类!”);

throw new RuntimeException(e);

}catch(SQLException e)

System.out.println(“数据库连接异常!”);

throw new RuntimeException(e);

}finally{

try{

if(rst != null){

rst.close();

}

if(stmt != null){

  stmt.close();

}

if(conn != null){

conn.close();

}

}catch(SQLException e){

System.out.println(“数据库关闭异常!”);

throw new RuntimeException(e);

}

}