从语句更改为PreparedStatements

时间:2013-11-06 14:56:52

标签: java mysql jdbc

我有一个简单的代码,可以将一些信息发送到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”它的变量与我的信息。 这个代码我在循环中,并且在每一步中我的变量(text_topic)的值都会改变。

我想用预备陈述代替我的决定。 怎么做?

2 个答案:

答案 0 :(得分:0)

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

// Prepare the statement - should only be done once, even if you are looping.
String sql = "insert into abcnews_topics VALUES (null, ?)";
PrepatedStatement stmt = connection.prepareStatement(sql);

// Bind varaibles
stmt.setString (1, text_topic); // Note that indexes are 1-based.

// Execute
stmt.executeUpdate();

答案 1 :(得分:0)

您应该参数化SQL,并调用prepareStatement

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

(try-with-resources语句将自动关闭PreparedStatement。如果您使用的是Java 6或更早版本,请使用try / finally块自行完成。)

请注意,我已将text_topic变量更改为textTopic以遵循Java命名约定,将stmt重命名为statement以避免缩写,并且还移动了声明statement到作业。 (早先宣布它是没有意义的:尽可能限制范围。)