JDBC PreparedStatement导致MySQL语法错误

我收到错误“你的SQL语法有错误;检查与你的MySQL服务器版本相对应的手册,以便在第1行使用”orderr”附近正确的语法” – 所以我假设错误就是我使用了两个但在我的代码中我没有使用任何 。 NB该表实际上命名为orderr。

public void insertIntoDatabase(String table, Object... entries) { // take a table and Connection con = connect(); //add entries PreparedStatement preparedStatement = null; PreparedStatement preparedStatement2 = null; ResultSet rs = null; StringBuffer columnNames = new StringBuffer(); StringBuffer sbEntries = new StringBuffer(); for (int i = 0; i < entries.length; i++) { if (entries[i] instanceof Integer) sbEntries.append((Integer) entries[i]); else if (entries[i] instanceof String) sbEntries.append((String) entries[i]); if (i != entries.length - 1)//if not last entry add sbEntries.append(" ,"); // a ' ,'. } try { preparedStatement = con.prepareStatement("select * from ? ;"); preparedStatement.setString(1, table); preparedStatement2 = con .prepareStatement("Insert into ?( ? ) values ( ? );"); ResultSet resultSet = preparedStatement.executeQuery(); // get the // number of // columns ResultSetMetaData rsmd; // for the table rsmd = resultSet.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i = 1; i < columnCount + 1; i++) { // get column names, add to columnNames.append(rsmd.getColumnName(i)); // to sb if (i != columnCount) columnNames.append(" ,"); } columnCount = rsmd.getColumnCount(); preparedStatement2.setString(1, table); preparedStatement2.setString(2, columnNames.toString()); //add sb's to statement preparedStatement2.setString(3, sbEntries.toString()); preparedStatement2.executeUpdate(); } catch (SQLException e) { System.out.println("2" + e.getMessage()); } finally{ try { if (rs != null) { rs.close(); } if (preparedStatement != null) { preparedStatement.close(); } if(preparedStatement2 != null){ preparedStatement2.close(); } if (con != null) { con.close(); } } catch (SQLException e) { System.out.print("3" +e.getMessage()); } } } 

在大多数数据库中,您无法参数化对象名称,例如表名,在MySQL中您理论上可以将MySQL Connector / J默认不使用服务器端参数,而是在将查询发送到服务器之前重写该查询。 但是,该值将作为带引号的字符串插入,并且对象名称不能是带引号的字符串,因此它仍然不起作用。

INSERT INTO ?SELECT ... FROM ? 将无法工作,因为它产生INSERT INTO 'theTable'SELECT ... FROM 'theTable'

对象名称必须是实际查询的一部分。 不要使用参数。 大多数其他数据库(或其驱动程序)会因为在此位置具有参数而抛出exception。

您的代码中有两个错误。

  1. 您不能使用预准备语句在SQL语句中设置表名。
  2. 你有; 在SQL语句中。

一旦你处理了以上几点,你的代码就可以了。