org.postgresql.util.PSQLException:错误:Java附近«,»附近的语法错误

时间:2013-09-29 01:36:10

标签: java postgresql jdbc

以下是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语句中执行,并在DB中正确插入值,但它也会抛出以下异常,在第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值,并且查询中显示了所有其他值。提前谢谢!

1 个答案:

答案 0 :(得分: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,因为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);
相关问题