简体   繁体   English

JDBC:使用PreparedStatement创建表,SQL语法错误与否?

[英]JDBC: Create Table with PreparedStatement, SQL Syntax Error or not?

I am encountering some difficulties trying to, in a dynamic way, create a new table using PreparedStatement. 我遇到了一些困难,试图以动态的方式使用PreparedStatement创建一个新表。 I am trying to add a unknown number of columns and their respective types and sizes. 我试图添加未知数量的列及其各自的类型和大小。 I keep getting SQL Syntax errors, but I suspect this may not be the case here. 我不断收到SQL语法错误,但我怀疑这可能不是这种情况。

Variables used: 使用的变量:

  • con = Connection object con =连接对象
  • colNames = String[] containing column names ("person", "email" etc) colNames = String []包含列名(“person”,“email”等)
  • colTypes = String[] containing column types ("varchar", "int" etc) colTypes =包含列类型的String [](“varchar”,“int”等)
  • colSizes = String[] containing column sizes ("100", "11", etc) colSizes = String []包含列大小(“100”,“11”等)

Should be pretty self-explanatory. 应该是不言自明的。

con.setAutoCommit(false);
String sql = "? ?(?),";
PreparedStatement ps = con.prepareStatement(sql);
ps.addBatch("create table " + tablename + "( ");

for (int i = 0; i < colNames.length; i++){

    if (!(i == colNames.length-1)) {
        ps.setString(1, colNames[i]);
        ps.setString(2, colTypes[i]);
        ps.setString(3, colSizes[i]);

    } else {
        String format = "%s %s(%s)";
        String lastLine = String.format(format, colNames[i], colTypes[i], colSizes[i]);
        ps.addBatch(lastLine);

    }
}

ps.addBatch(");");
ps.executeBatch();

NOTE: Yes, this is homework. 注意:是的,这是作业。 I don't want any dead giveaways, rather pointers as to in what way I am misusing some functions, which I suspect. 我不想要任何死的赠品,而是指示我以何种方式滥用某些功能,我怀疑。

Best regards, Krys 最好的问候,Krys

You need to give the full SQL statement to addBatch. 您需要将完整的SQL语句提供给addBatch。 It is not a tool to construct a dynamic SQL statement. 它不是构造动态SQL语句的工具。 It is a tool to improve performance when running multiple statements. 它是一种在运行多个语句时提高性能的工具。 You don't need it here. 你在这里不需要它。

You also don't need a PreparedStatement here, as you are not going to have bind variables (ie column data as opposed to column names) and are not going to run the same SQL repeatedly (but it does not hurt, either). 你也不需要这里的PreparedStatement,因为你不会有绑定变量(即列数据而不是列名),并且不会重复运行相同的SQL(但它也没有受到伤害)。 setString and friends do not work for column or table names, just for data. setString和friends不适用于列名或表名,仅适用于数据。

A StringBuilder is a good tool to construct a String with variable parts. StringBuilder是构造具有可变部分的String的好工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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