我如何做好准备好的陈述? [英] How do I make a prepared statement?

查看:120
本文介绍了我如何做好准备好的陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何准备好这个声明?

    Statement stmt = con.createStatement();

    long lastid = getLastId(stmt);

    // create a SQL query
    String strQuery = "INSERT INTO studenten " +
    " (id, naam, adres, postcode, plaats, geboren) " +
    " VALUES (" + (lastid+1) + "," +
        "'" + contact.getNaam() + "'," +
        "'" + contact.getAdres() + "'," +
        "'" + contact.getPostcode() + "'," +
        "'" + contact.getPlaats() + "'," +
      "{d '" + contact.getGeboren() + "'}" +
    ") ";

    stmt.executeUpdate(strQuery);      
    stmt.close();
    con.close();


推荐答案

您需要用带有问号<$ c的值替换值$ c>?作为占位符。

You need to substitute values with question marks ? as placeholders.

String sql = "INSERT INTO studenten (id, naam, adres, postcode, plaats, geboren)"
     + " VALUES (?, ?, ?, ?, ?, ?)";
Connection connection = null;
PreparedStatement statement = null;

try {
    connection = database.getConnection();
    statement = connection.prepareStatement(sql);
    statement.setLong(lastId + 1); // Why don't you use an generated sequence? This is plain ugly and errorprone.
    statement.setString(contact.getNaam());
    statement.setString(contact.getAdres());
    statement.setString(contact.getPostcode());
    statement.setString(contact.getPlaats());
    statement.setDate(new java.sql.Date(contact.getGeboren().getTime())); // Assuming it returns java.util.Date
    statement.executeUpdate();
} finally {
    // Always close in finally to prevent resource leaks.
    if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
    if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}



参见:




  • JDBC教程 - 使用预准备语句

  • See also:

    • JDBC tutorial - Using prepared statements
    • 这篇关于我如何做好准备好的陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆