Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the query contains string constant within the <code>values</code> clause, as you have shown in the question:</p> <pre><code>query = "insert into table(cedula, actividad, mercado) " + " values ('val', 'GAM', 'GAM' )"; </code></pre> <p>then this part of code will work fine:</p> <pre><code>conexion.createStatement().execute(query); </code></pre> <p>however this part of code won't work:</p> <pre><code>pstmt.setString(1, n.getCedula()); //the rest of the sets of the statement continue here from 1 to 13 </code></pre> <p>It will throw an <code>PSQLException: The column index is out of range: X, number of columns: 0</code>, because <code>PreparedStatement.setXXX</code> methods expect placeholders <code>?</code> in the SQL statement.<br> On the other hand, when the insert statement contains placeholders (I assume that your INSERT <strong>does contain</strong> placeholders, because you haven't got the above exception):</p> <pre><code>query = "insert into tabla(cedula, actividad, mercado) " + " values ( ?, ?, ? )"; </code></pre> <p>then <code>pstmt.setString...</code> statements will work fine, however this statement:</p> <pre><code> conexion.createStatement().execute(query); </code></pre> <p>will throw an exception: <code>PSQLException: ERROR: syntax error near ','</code> <br> If your intent is to execute the INSERT twice, the first one using placeholders, and the second one using string values, you must do it in this way:</p> <pre><code>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); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload