SQL语法错误创建表

时间:2014-05-15 20:40:33

标签: java mysql jdbc

当我尝试在SQL数据库中创建表时,我收到以下错误:

Failed to create table 'references'
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 'references(referenceID BIGINT NOT NULL AUTO_INCREMENT, 
referenceText VARCHAR(255)'

以下是制作表格的代码:

public void createReferencesTable() {
    System.out.println("Creating table '" + REFERENCE_TABLE + "'...");
    Statement stmt = null;
    try {
        stmt = connection.createStatement();
        stmt.executeUpdate("CREATE TABLE " + REFERENCE_TABLE + "("
                + REFERENCE_ID + " BIGINT NOT NULL AUTO_INCREMENT,"
                + REFERENCE_TEXT + " VARCHAR(255),"
                + REFERENCE_TWEET + " BIGINT NOT NULL,"
                + "PRIMARY KEY (" + REFERENCE_ID + ")"
                + ")");
        System.out.println("Table '" + REFERENCE_TABLE + "' created");
    } catch (SQLException e) {
        System.err.println("Failed to create table '" + REFERENCE_TABLE + "'");
        e.printStackTrace();
    } finally {
        if (stmt != null) { 
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } 
        }
    }
}

以下是所用变量的声明:

public static final String REFERENCE_TABLE = "references";
public static final String REFERENCE_ID = "referenceID";
public static final String REFERENCE_TEXT = "referenceText";
public static final String REFERENCE_TWEET = "referenceTweet";

另外,我在这个之前创建了两个表,它们成功地使用了基本上与此语法完全相同的语法,这是失败的。此外,我将这些数据库放入的MySQL服务器是新鲜的,只是设置,所以不应该有任何配置问题,因为我的程序成功连接到数据库。

我的问题是:为什么会出错?

注意:我尝试使用标识执行引用ID行,但这没有任何区别。正如我之前所说,在此之前创建表的两个函数使用完全相同的语法,但没有给出错误并成功创建了表。

1 个答案:

答案 0 :(得分:1)

references是MySQL中的reserved word。要么使用反引号来逃避它,要么使用其他名称。

stmt.executeUpdate("CREATE TABLE `" + REFERENCE_TABLE + "` ("
                                 ^-----------------------^-----------here
相关问题