Inserting preparedstatement to database - PSQL

前端 未结 1 1037
情话喂你
情话喂你 2020-12-20 09:17

This seems like a really simple problem, but I cannot figure out what my problem is. I have a method addTask which adds some info to our database as seen in this code:

相关标签:
1条回答
  • 2020-12-20 09:54

    You misunderstood the return value of PreparedStatement#execute().

    Please carefully read the javadoc:

    Returns:

    true if the first result is a ResultSet object; false if the first result is an update count or there is no result.

    It thus returns — as fully expected — false on an INSERT query. It returns only true on a SELECT query (for which you'd however usually like to use executeQuery() instead which returns directly a ResultSet).

    If you're interested in the affected rows, rather use PreparedStatement#executeUpdate() instead. It returns an int as per the javadoc:

    Returns:

    either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

    A return value of 1 or greater would then indicate a successful insert.


    Unrelated to the concrete problem: your code is leaking DB resources. Please carefully read How often should Connection, Statement and ResultSet be closed in JDBC?

    0 讨论(0)
提交回复
热议问题