![](/img/trans.png)
[英]JDBC: Create Table with PreparedStatement, SQL Syntax Error or not?
[英]Cant create table with preparedStatement
我不能在數據庫中創建(MySQL的)表,使用preparedStatement
並嘗試進入未來表的名稱preparedStatement.setInteger()
static String queryCreateTable = "CREATE TABLE ?" +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
然后我嘗試在用戶輸入表名后構造並調用該語句:
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
pStatement = connection.prepareStatement(queryCreateTable);
pStatement.setString(1, newNameOfTable);
pStatement.executeUpdate();
如果我嘗試在不輸入名稱的情況下執行它(如常量字符串:“CREATE TABLE newtable (...)”但我需要輸入名稱..
讀取表名后,您必須格式化字符串,例如:
static String queryCreateTable = "CREATE TABLE {0}" +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
然后創建如下:
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
statement = connection.createStatement();
statement.execute(MessageFormat.format(queryCreateTable, newNameOfTable));
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
static String queryCreateTable = "CREATE TABLE " + newNameOfTable +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
pStatement = connection.prepareStatement(queryCreateTable);
pStatement.executeUpdate();
PreparedStatement 示例: http : //tutorials.jenkov.com/jdbc/preparedstatement.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.