我一直在尝试使用这段代码在数据库中创建一个表,在此之前的代码已成功创建。
//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 的无能,但也许这里有人可以看到我的语法错误。谢谢!
最佳答案
USE inventory;
语句不适用于 JDBC 连接上下文。您需要使用 Connection#setCatalog()切换到特定的数据库。更多详细信息,请参阅
Java, how to change current database to another?
这样做并从您的 SQL 中删除 USE 子句。
关于java - 尝试切换到(使用)数据库时出现 JDBC "Error in MySQL Syntax",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33585758/