change from Statements to PreparedStatements

I have a simple code which sending some info into mysql.

        Connection connection = null;
        Statement stmt;

        Properties connInfo = new Properties();
        connInfo.put("user", "Main");
        connInfo.put("password", "poiuyt");
        connection  = DriverManager.getConnection("jdbc:mysql://localhost/ABCNews", connInfo);


        String sql = "insert into abcnews_topics VALUES (null, '" + text_topic + "');";
        stmt = (Statement) connection.createStatement();
        stmt.executeUpdate(sql);

"text_topic" it`s variable with my info. this code i have in cycle, and in each step the value of my variable (text_topic) changes.

and i want to use Prepared Statements instead my decision. how to do it?

Jon Skeet
people
quotationmark

You should parameterize your SQL, and call prepareStatement:

String sql = "insert into abcnews_topics VALUES (null, ?)";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
    statement.setString(1, textTopic);
    statement.execute();
}

(The try-with-resources statement will close the PreparedStatement automatically. If you're using Java 6 or earlier, use a try/finally block to do it yourself.)

Note that I've changed the text_topic variable to textTopic to follow Java naming conventions, renamed stmt to statement to avoid abbreviation, and also moved the declaration of statement to the assignment. (There's no point in declaring it earlier: try to limit scope where possible.)

people

See more on this question at Stackoverflow