There is such a construction

String query = "INSERT INTO database.postinfo (post_id) \n" + " VALUES ('id' );"; try { con = DriverManager.getConnection(url, user, password); stmt = con.createStatement(); stmt.executeUpdate(query); } catch (SQLException sqlEx) { sqlEx.printStackTrace(); } finally { //close connection and stmt heare try { con.close(); } catch (SQLException se) { /*can't do anything */ } try { stmt.close(); } catch (SQLException se) { /*can't do anything */ } } 

I want the values ​​of the variables to be passed to VALUES. For example, I have a variable obtained using Jsoup, and I want to pass it to VALUES to populate the post_id column, but in my example above, only the text 'id' is transmitted (literally), not the value of the variable.

 id = doc.select("div.story").attr("data-story-id") 

    1 answer 1

    Properly use prepared statement. To do this, in the sql query, replace all external parameters with question marks, and then set the value for each of the parameters using the methods stmt.set... The numbering of the parameters starts from one.
    For example:

     String query = "INSERT INTO database.postinfo (post_id, some_int) VALUES (?, ?)"; //... PreparedStatement stmt = con.prepareStatement(query); stmt.setString(1, "your-id"); // 1 - порядковый номер параметра ("?") внутри запроса stmt.setInt(2, 456); stmt.executeUpdate(); 

    where "your-id" and 456 should be replaced with the desired values. With this approach, there will be no errors due to special characters in the passed parameters.

    • those. for each parameter you need to write a separate PreparedStatement? - Roman DriveMind
    • @ NovelDriveMind No, there can be several parameters in one request. Let me complete the example. - Roman
    • I understand everything. thanks - Roman DriveMind