以下是Java中prepareStatement生成的查询:

insert into schema.table(cedula, actividad, mercado, venta_mensual, fortalezas, crecer,
 financiamiento, monto, patente, contador, regimen_tri, problemas, bn_servicios, cursos )
values ('val', 'GAM', 'GAM', '0', 'Calidad', 'Sí', 'Sí', '122', 'Sí', 'Sí', 'ddd', 'aaa','ccc', 'bbb'  )


Java代码是:

try {
    PreparedStatement pstmt = conexion.prepareStatement(query);
    pstmt.setString(1, n.getCedula());
        //the rest of the sets of the statement continue here from 1 to 13
        pstmt.executeUpdate();
    conexion.createStatement().execute(query);
        return true
} catch (SQLException e) {
    e.printStackTrace(); // This error
    return false;
}


该查询将在try语句中执行,并将值正确插入数据库中,但同时也会在行192处抛出以下异常:此处为“ val”:

 org.postgresql.util.PSQLException: ERROR: error de sintaxis en o cerca de «,»
 org.postgresql.util.PSQLException: ERROR: syntax error near ',' java


与postgres有关的错误跟踪在这里:

at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:366)


顺便说一句,该表具有一个大序列值,并且所有其他值都显示在查询中。提前致谢!

最佳答案

如问题所示,如果查询在values子句中包含字符串常量,则:

query = "insert into table(cedula, actividad, mercado) "
        + " values ('val', 'GAM', 'GAM' )";


那么这部分代码可以正常工作:

conexion.createStatement().execute(query);


但是这部分代码无法正常工作:

pstmt.setString(1, n.getCedula());
//the rest of the sets of the statement continue here from 1 to 13


它将抛出一个PSQLException: The column index is out of range: X, number of columns: 0,因为PreparedStatement.setXXX方法在SQL语句中需要占位符?
另一方面,当insert语句包含占位符时(我假设您的INSERT确实包含占位符,因为您没有上面的异常):

query = "insert into tabla(cedula, actividad, mercado) "
    + " values ( ?, ?, ? )";


那么pstmt.setString...语句将正常工作,但是此语句:

   conexion.createStatement().execute(query);


将引发异常:PSQLException: ERROR: syntax error near ','

如果您打算执行两次INSERT,第一个使用占位符,第二个使用字符串值,则必须以这种方式执行:

query1 = "insert into tabla(cedula, actividad, mercado) "
        + " values ('val', 'GAM', 'GAM' )";
query2 = "insert into tabla(cedula, actividad, mercado) "
        + " values ( ? , ? , ? )";

PreparedStatement pstmt = conexion.prepareStatement(query2);
pstmt.setString(1, n.getCedula());
  //the rest of the sets of the statement continue here from 1 to 13
pstmt.executeUpdate();

conexion.createStatement().execute(query1);

08-06 07:58