【问题标题】:JDBC "Error in MySQL Syntax" when trying to switch to (USE) a database尝试切换到(使用)数据库时出现 JDBC“MySQL 语法错误”
【发布时间】:2016-02-08 17:16:14
【问题描述】:

我一直在尝试使用此代码在数据库中创建一个表,之前的代码已成功创建。

//Creates "Parts" Table if it's not already created.
public void createTableIfNecessary() throws SQLException{
String createString =
        "USE inventory; " +
        "CREATE TABLE IF NOT EXISTS parts " +
                "(part_name TEXT NOT NULL, remaining_amt INT NOT NULL, " +
                "restock_amt INT, barcode TEXT, location TEXT, part_id INT NOT NULL AUTO_INCREMENT);";
Statement createTable = this.con.createStatement();
createTable.execute(createString);
System.out.println("Table created or already existed: Parts");
}

我的连接数据库服务器的代码:

    try{Class.forName("com.mysql.jdbc.Driver");} catch(Exception e){
        e.printStackTrace();
    }
    this.con = null;
    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);
    this.con = DriverManager.getConnection("jdbc:mysql://" + this.serverName + ":" + this.portNumber + "/", connectionProps);
    System.out.println("Connected to MySQL Database Server");

(这行得通,但看看可能会有所帮助)

我的错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE IF NOT EXISTS parts (part_name TEXT NOT NULL, remaining_amt INT NOT' at line 1

我认为这只是我对 MySQL 的无能,但也许这里有人可以看到我的语法错误。谢谢!

【问题讨论】:

    标签: java mysql jdbc


    【解决方案1】:

    USE inventory; 语句不适用于 JDBC 连接的上下文。您需要使用Connection#setCatalog() 切换到特定数据库。更多详情,请参阅

    Java, how to change current database to another?

    这样做并从您的 SQL 中删除 USE 子句。

    【讨论】:

    • 非常感谢!我一直找不到那个答案。我会在几分钟后将其标记为正确。
    • 虽然您不应该在 JDBC 中使用 USE ... 是正确的,但据我所知,这不是导致此异常的原因。更可能的原因是 OP 同时执行了两条语句,这是 JDBC 所不允许的,因此只有在具有连接属性的 Connector/J 驱动程序中显式启用它时才有效。
    • @MarkRotteveel 谢谢你的回答。我认为这确实是这里的问题,我一定在文档中错过了!
    【解决方案2】:

    对于 mysql 中的 auto_increment 列,它必须被索引。因此,您必须通过将 part_id 设为主键或唯一键来对其进行索引。

    CREATE TABLE IF NOT EXISTS parts
    (part_name TEXT NOT NULL, 
     remaining_amt INT NOT NULL, 
     restock_amt INT, 
     barcode TEXT, 
     location TEXT, 
     part_id INT NOT NULL AUTO_INCREMENT,
    primary key (part_id));
    

    【讨论】:

      猜你喜欢
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多