Java 使用JDBC加速postgresql上的sql插入?

Java 使用JDBC加速postgresql上的sql插入?,java,postgresql,jdbc,Java,Postgresql,Jdbc,下面有两种方法用于检查数据库中是否有匹配项,如果没有,则调用insert方法。我的程序需要经过数千行,这需要很长时间。我做得不对吗?我能做些什么来显著加快速度 public Boolean isMatchIdInDatabase(String matchId) throws SQLException { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; Boolea

下面有两种方法用于检查数据库中是否有匹配项,如果没有,则调用insert方法。我的程序需要经过数千行,这需要很长时间。我做得不对吗?我能做些什么来显著加快速度

public Boolean isMatchIdInDatabase(String matchId) throws SQLException
{
    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    Boolean exists = false;

    try
    {
        Class.forName("org.postgresql.Driver");
        conn = DriverManager.getConnection(url, props);
        pst = conn.prepareStatement("SELECT COUNT(*) FROM match where match_id = ?");
        pst.setString(1, matchId);

        rs = pst.executeQuery();
        while (rs.next())
        {
            exists = rs.getBoolean(1);
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        pst.close();
        rs.close();
        conn.close();
    }

    return exists;
}

public Boolean insertMatchId(String matchId, String name, Timestamp birthdate, String bio, String accountId) throws SQLException, ClassNotFoundException
{
    Connection conn = null;
    PreparedStatement pst = null;
    Boolean exists = false;

    try
    {
        Class.forName("org.postgresql.Driver");
        conn = DriverManager.getConnection(url, props);
        pst = conn.prepareStatement("INSERT INTO match (match_id, name, birthdate, bio, account_id) values(?, ? , ?, ?, ?)");
        pst.setString(1, matchId);
        pst.setString(2, name);
        pst.setTimestamp(3, birthdate);
        pst.setString(4, bio);
        pst.setString(5, accountId);

        pst.executeUpdate();

    }
    finally
    {
        pst.close();
        conn.close();
    }

    return exists;
}

您可以尝试使用
WHERE NOT EXISTS
将插入行的SQL查询更改为仅当该行不在数据库中时才插入。 这篇文章似乎很相关——我知道它是针对MySQL而不是PostgreSQL的,但原则应该是一样的。

您是先调用
isMatchidDatabase
然后调用
insertMatchId
来查找许多记录吗? 可能重复:


打开连接并查询单个记录是一项昂贵的操作。如果你这样做数千次,它会变得非常缓慢。您应该尝试重新构造查询,以便只使用一个
SELECT
。然后,您可以收集必须插入的记录,并使用批插入进行插入

我认为你给我的链接应该添加连接的详细信息