0

以下是由 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)

顺便说一句,该表有一个 bigserial 值,所有其他值都显示在查询中。提前致谢!

4

1 回答 1

2

如果查询在子句中包含字符串常量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, 因为方法需要 SQL 语句中的PreparedStatement.setXXX占位符。 另一方面,当插入语句包含占位符时(我假设您的 INSERT确实包含占位符,因为您没有遇到上述异常):?

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

thenpstmt.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);
于 2013-09-29T11:20:36.370 回答