繁体   English   中英

不能用preparedStatement创建表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM