-1

我有一个简单的代码,可以将一些信息发送到 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)的值都会发生变化。

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

4

2 回答 2

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();
于 2013-11-06T15:00:43.950 回答
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 命名约定,重命名stmtstatement以避免缩写,并将声明移至statement赋值。(提前声明是没有意义的:尽可能限制范围。)

于 2013-11-06T15:01:15.223 回答