【问题标题】:java.sql.SQLException: No database selected [duplicate]java.sql.SQLException:未选择数据库[重复]
【发布时间】:2014-12-17 06:01:29
【问题描述】:

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

我正在使用 xampp,在那里我在 MySQL 中创建了一个数据库并将其命名为“employees”

这是我的java代码:

 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访问数据库

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

【问题讨论】:

    标签: java mysql database jdbc


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 2016-02-14
        • 2021-03-31
        • 2019-07-26
        • 2020-11-06
        • 2014-08-26
        • 2020-03-23
        相关资源
        最近更新 更多