无法使用preparedStatement

时间:2015-11-09 17:11:59

标签: java mysql sql

我无法使用preparedStatement在数据库(mySQL)中创建一个表,并尝试使用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(...)"它可以正常工作但我需要输入名称..

2 个答案:

答案 0 :(得分:1)

您必须在读取表名后格式化字符串,例如:

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));

答案 1 :(得分:0)

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