为什么以下语句会导致SyntaxErrorException?

时间:2015-06-09 09:26:41

标签: java mysql jdbc

我正在尝试使用JDBC创建表,但我在查询时遇到语法错误。

Statement statement = con.createStatement();
String query = "CREATE TABLE accounts (user VARCHAR2(255) NOT NULL,
                                       password VARCHAR2(255) NOT NULL,
                                       dateRegistered date "+
                                      "primary key (user));";

statement.executeUpdate(query);
System.out.println("part 2:DONE !"); 

这是错误:

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 'VARCHAR2(255) NOT NULL, password VARCHAR2(255) NOT NULL, dateRegistered date, pr' at line 1    
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)    
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)    
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)    
at java.lang.reflect.Constructor.newInstance(Unknown Source)    
at com.mysql.jdbc.Util.handleNewInstance(Util.java:389)    
at com.mysql.jdbc.Util.getInstance(Util.java:372)    
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980)    
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3835)    
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3771)    
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)    
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)    
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2531)    
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2489)    
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:848)    
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:742)    
at Test.main(Test.java:26)

1 个答案:

答案 0 :(得分:1)

假设您使用的是MySQL

MySQL不支持VARCHAR2,因此请将其替换为VARCHAR

在主键之前添加comma

String query = "CREATE TABLE accounts (user VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, dateRegistered date, primary key (user));";