0
public void insertTags(Elements[] elements) {

    Connection con = (Connection) DbConnection.getConnection();

    try {
        String sql = "insert into htmltags(source) values(?),(?),(?)";
        PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
        ps.setString(1, elements[0].toString());
        ps.setString(2, elements[1].toString());
        ps.setString(3, elements[2].toString());
        int rs = ps.executeUpdate(sql);
        System.out.println("Data inserted" + rs);

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

is this a valid syntax for Prepared statement.

2
  • 2
    You can't insert 3 values into one column "source", and the syntax would need to be values(?,?,?). Commented Jan 23, 2018 at 11:11
  • What is values(?),(?),(?) Commented Jan 23, 2018 at 11:12

2 Answers 2

2

This is your problem:

int rs = ps.executeUpdate(sql);

From the JavaDoc we see that PreparedStatement#executeUpdate() does not take any parameters. The reason is that we already passed the query earlier when preparing the statement. Your code should be this:

int rs = ps.executeUpdate();  // no parameter

Also no need to cast the result of prepareStatement to PrepareStatement

Sign up to request clarification or add additional context in comments.

2 Comments

Of note, many tutorials also seem to make this mistake (e.g. MkYong, at least as of several months ago when I last checked).
in fact its incorrect here. Maybe youre trying to concatenate values. In that case only use one placeholder and concatenate in the java code...
0

To insert multiple values, I don't thing using values(?),(?),(?) is the right syntax, instead use a loop, or for better way you can use batch :

String sql = "insert into htmltags(source) values(?)";
try (PreparedStatement ps = con.prepareStatement(sql);) {
    for (Elements element : elements) {
        ps.setString(1, element.toString());
        ps.addBatch();//Add a new batch for each Element
    }

    int[] result = ps.executeBatch();//Submits a batch of commands to the database

} catch (SQLException e) {
    e.printStackTrace();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.