尝试以Java连接到PostgreSQL数据库时出现org.postgresql.util.PSQLException

时间:2019-03-15 03:47:18

标签: java sql postgresql

我的错误发生在preparedStatement.executeUpdate();语句上,并引发以下异常:

Exception in thread "main" org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
  Position: 65
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)
    at Main.main(Main.java:28)

这是我的代码:

import java.sql.*;

import Helper.DBHandler;

public class Main {

    private static Connection connection;
    private static PreparedStatement preparedStatement;

    public static void main(String[] args) throws ClassNotFoundException, SQLException {


        connection  = new DBHandler().getDbConnection();

        String sqlInsert = "INSERT INTO users(firstname,lastname,username,address,age)"
                         + "VALUES ?,?,?,?,?";


        preparedStatement = connection.prepareStatement(sqlInsert);

        System.out.println(connection.getNetworkTimeout());

        preparedStatement.setString(1,"John");
        preparedStatement.setString(2,"Doe");
        preparedStatement.setString(3,"jondo");
        preparedStatement.setString(4,"Tokyo Japan");
        preparedStatement.setInt(5,28);
        preparedStatement.executeUpdate();
    }
}

这是DBHandler类,其中config包含变量dbhostdbPort等。我验证了这部分的功能。

package Helper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBHandler extends Config{

    public Connection getDbConnection() throws ClassNotFoundException, SQLException {

        String connectionString = "jdbc:postgresql://" + dbHost + ":" + dbPort + "/" + dbName;

        Class.forName("org.postgresql.Driver");

        return  DriverManager.getConnection(connectionString, dbUser, dbPass);

    }

}

1 个答案:

答案 0 :(得分:4)

您需要将要插入的元组放在括号内。因此,请使用以下SQL:

INSERT INTO users (firstname, lastname, username, address, age)
VALUES (?,?,?,?,?);

您更新的Java代码:

String sqlInsert = "INSERT INTO users (firstname, lastname, username, address, age) ";
sqlInsert += "VALUES (?,?,?,?,?)";

请注意,如果您不喜欢括号,则可以将当前的占位符语法与INSERT INTO ... SELECT一起使用:

INSERT INTO users (firstname, lastname, username, address, age)
SELECT ?, ?, ?, ?, ?;