[英]JDBC “Error in MySQL Syntax” when trying to switch to (USE) a database
我一直在嘗試使用此代碼在數據庫中創建一個表,該代碼在此數據庫之前成功創建。
//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()切換到特定的數據庫。 有關更多詳細信息,請參見
這樣做,然后從SQL中刪除USE子句。
對於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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.