【问题标题】:change from Statements to PreparedStatements从 Statement 更改为 PreparedStatements
【发布时间】:2013-11-06 14:56:52
【问题描述】:

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

我想使用Prepared Statements代替我的决定。 怎么办?

【问题讨论】:

  • 网上很多例子,你都没搜过吗?
  • 我当然会搜索,但我的测试总是出错。

标签: java mysql jdbc


【解决方案1】:
// 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();

【讨论】:

    【解决方案2】:

    你应该参数化你的 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 的声明移至赋值。 (提前声明是没有意义的:尽量限制范围。)

    【讨论】:

      猜你喜欢
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      相关资源
      最近更新 更多