Java.sql.SQLException:为什么没有选择数据库?

13


最近我一直在尝试学习如何通过Java访问mySQL数据库。 我已经成功加载了驱动程序并连接到了数据库(至少我认为是这样,因为没有出现异常..)

代码如下:

    import java.sql.*;
    public class test
    {
        public static void main(String[] args)
        {
            try
            {
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              System.out.println("driver loaded...");
            }
            catch(ClassNotFoundException e){
              System.out.println("Error in loading the driver..."+e);
              System.exit(0);
            }
            try
            {
                Connection dbConnection= DriverManager.getConnection("jdbc:odbc:test","root","password");
                System.out.println("Connection successful...");
                Statement stmt = dbConntection.createStatement();
                stmt.executeUpdate("create table Accounts ( name char(20) )");
             }
             catch(SQLException e)
             {
                  System.out.println("database-ConnectionError: "+e);
                  System.exit(0);
             }   
        }
    }

当我执行它时,显示:

驱动程序已加载...
连接成功...
数据库连接错误:java.sql.SQLException:[MySQL] [ODBC 5.2(w)Driver] [mysqld-5.5.31]未选择数据库

我真的不知道问题在哪里,因为我认为在“getConnection”过程中选择了数据库....
我尝试通过添加这行代码来选择数据库:

    stmt.executeUpdate("use test;");

在创建Statement之后。

不幸的是,它没有奏效,因为我收到了另一个异常,提示我应该检查语法。我也不理解,因为在命令行中它可以正常工作...如果不能通过Java使用这些类型的命令,那么请原谅我的错误。

我希望你能帮助我,我希望在自己的搜索中没有错过解决方案!

感谢所有回复并花时间解决我的问题!

附注:如果我忘记指出一些重要信息(我认为我没有),请提出询问:)

编辑:我也尝试在运行时创建一个新的数据库

     stmt.executeUpdate("CREATE DATABASE test;");

这实际上是有效的,但数据库也不会被选中...


顺便提一下:使用JDBC驱动程序时,不应该使用像use <database>这样的命令来在数据库之间切换。相反,您应该使用setCatalog和/或setSchema(或在连接字符串中指定数据库)。使用use <database>可能会导致驱动程序出现错误行为。 - Mark Rotteveel
4个回答

12

在添加表格之前,您首先必须选择一个数据库。您可以使用以下方法创建新的数据库:

  CREATE DATABASE database_name

您可以使用以下代码连接到特定的数据库:

String url = "jdbc:mysql://localhost/databasename";
String username = "test";
String password = "test";
Connection connection = DriverManager.getConnection(url, username, password);

我也遇到了同样的问题。抱歉,我忘记说了... 数据库已创建但仍未被选中... 我该怎么做? - sepphuber3
我通过将连接数据库的URL与本地主机和数据库名称相结合来连接我的数据库,如果您正在运行本地主机,则为localhost/databasename。 - Stefan Pante
更新了我的答案,说明了我如何连接到我的数据库。这种方法在我的程序中运行良好。 - Stefan Pante
我相信这是可能的。但是,为什么你想使用ODBC而不是MySQL呢?http://dev.mysql.com/downloads/connector/j/ - Stefan Pante

7

首先,我考虑我的答案来展示给你另一种更好的连接MySQL数据库的方式,这种方式更加简单,并且减少了不必要的意外异常。注意:您需要执行以下步骤:

  1. Download Connector/J and add it to your class path(if you are using an IDE there is add the .jar to the library, or there is many tuts on YouTube).
  2. Create your database in your MySQL program.
  3. See this example below example below I made for you demonstrates how to connect and execute queries on MySQL :

    import java.sql.*;
    
    public class MySqlConnection {
      private String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
      private String MYSQL_URL = "jdbc:mysql://localhost:3306/test";
    
      private Connection con;
      private Statement st;
      private ResultSet rs;
    
      public MySqlConnection() {
    
        try {
          Class.forName(MYSQL_DRIVER);
          System.out.println("Class Loaded....");
          con = DriverManager.getConnection(MYSQL_URL,"","");
          System.out.println("Connected to the database....");
          st = con.createStatement();
          int c =st.executeUpdate("CREATE TABLE Accounts (Name VARCHAR(30))");
          System.out.println("Table have been created.");
          System.out.println(c+" Row(s) have been affected");
          con.close();
    
        } catch(ClassNotFoundException ex) {
           System.out.println("ClassNotFoundException:\n"+ex.toString());
           ex.printStackTrace();
    
        } catch(SQLException ex) {
            System.out.println("SQLException:\n"+ex.toString());
            ex.printStackTrace();
        }
      }
    
      public static void main(String...args) {
        new MySqlConnection();
      }
    }
    

@sepphuber3:不用谢,也许是ODBC(不确定) :)。 - Azad

1
这是您的更新示例,对我有效。
public static void main(String[] args) throws InstantiationException,
        IllegalAccessException {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        System.out.println("driver loaded...");
    } catch (ClassNotFoundException e) {
        System.out.println("Error in loading the driver..." + e);
        System.exit(0);
    }
    try {
        Connection dbConnection = DriverManager
                .getConnection("jdbc:mysql://localhost/test?user=root&password=password");
        System.out.println("Connection successful...");
        Statement stmt = dbConnection.createStatement();
        stmt.executeUpdate("create table Accounts ( name char(20) )");
    } catch (SQLException e) {
        System.out.println("database-ConnectionError: " + e);
        System.exit(0);
    }
}

请确保您已将适当的mysql-connector添加到构建路径中。我使用的是:mysql-connector-java-5.1.24-bin.jar


谢谢!我明天会尝试使用你用的连接器!我真的希望我能让它运行起来^^ - sepphuber3

1
static final String DB_URL = "jdbc:mysql://localhost:3306/sys";

在URL中使用数据库名称。 这对我很有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接