关于mysql:java.sql.SQLException:未选择数据库

java.sql.SQLException: No database selected

本问题已经有最佳答案,请猛点这里访问。

如上所述,我在"选择数据库"时遇到问题

我正在使用xampp,在那里我在MySQL中创建了一个数据库并将其命名为"员工"。

这是我的Java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 public static void main(String[] args) {
 Connection conn = null;
 Statement stmt = null;
 try{
  //STEP 2: Register JDBC driver
  Class.forName("com.mysql.jdbc.Driver");

  //STEP 3: Open a connection
  System.out.println("Connecting to database...");
  conn = DriverManager.getConnection("jdbc:mysql://localhost?user=root&password=");

  //STEP 4: Execute a query
  System.out.println("Creating statement...");
  stmt = conn.createStatement();
  String sql;
  sql ="SELECT id, first, last, age FROM employees";
  ResultSet rs = stmt.executeQuery(sql);

如在" sql"中所见,我尝试使用FROM employees

来访问数据库

我是数据库编程新手。
我需要查找数据库的路径吗?我如何以及在哪里可以找到它?


更改连接字符串以使其连接到本地主机上的正确数据库

1
conn = DriverManager.getConnection("jdbc:mysql://localhost/employees?user=root&password=");

或者,您可以指定表的"完整"路径,即database.tablename

1
sql ="SELECT id, first, last, age FROM employees.employees";


您需要在连接字符串中指定要使用的数据库:

1
conn = DriverManager.getConnection("jdbc:mysql://localhost/employees?user=root&password=");