如何在preparedstatement中使用JDBC通配符来创建mysql表

时间:2016-06-17 15:56:18

标签: java mysql jdbc

    String sql2 = "create table ? ( id int not null auto_increment, fullname
    varchar(30) not null, primary key (id) )";

    PreparedStatement stmt2 = conn.prepareStatement(sql2);

    stmt2.setString(1, username);

    stmt2.execute();

    stmt2.close();

从上述陈述中,我收到了错误消息(' john'作为表名):

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 ''john' ( id int not null 
auto_increment, fullname varchar(30) not null, primary ' at line 1
eclipse说错误就在这一行:

stmt2.execute();

请帮助大家...... tq

1 个答案:

答案 0 :(得分:1)

您不能在CREATE TABLE语句中为表名使用参数。

而只是使用变量

构建SQL字符串
String sql2 = "create table " + username + " ( id int not null auto_increment, fullname
varchar(30) not null, primary key (id) )";

Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(sql2); 
相关问题