我如何做出准备好的陈述?

Posted

技术标签:

【中文标题】我如何做出准备好的陈述?【英文标题】:How do I make a prepared statement? 【发布时间】:2010-09-13 12:47:49 【问题描述】:

我怎样才能对这个做一个准备好的陈述?

    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();

【问题讨论】:

你使用的是什么数据库系统? 【参考方案1】:

您需要用问号? 替换值作为占位符。

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 tutorial - Using prepared statements

【讨论】:

谢谢!lastID 只是我需要编辑的源代码的一部分,不知道他们为什么使用【参考方案2】:

这是一个更好的方法:

String sql = "INSERT INTO studenten (id, naam, adres, postcode, plaats, geboren)"
     + " VALUES (?, ?, ?, ?, ?, ?)"

try 
    connection = database.getConnection();
    statement = connection.prepareStatement(sql);
    statement.setLong(1,your_id_value);
    statement.setString(2,contact.getNaam());
    statement.setString(3,contact.getAdres());
    statement.setString(5,contact.getPlaats());  // order doesn't matter now you can give the index of the parameter
    statement.setString(4,contact.getPostcode());
    statement.setDate(6,getGeboren());
    statement.executeUpdate();

    // or System.out.println(statement.executeUpated())  to see how many row are effected by this query
    statement.close();
 catch(java.sql.Exception sql_exception )
    //you can see what goes wrong here with your statement 
    e.printStackTrace();

【讨论】:

以上是关于我如何做出准备好的陈述?的主要内容,如果未能解决你的问题,请参考以下文章

我需要坚持准备好的陈述吗?

PDO准备好的陈述[关闭]

什么是准备好的陈述?

PHP 准备好的陈述:阅读

准备好的陈述:阅读

Golang使用准备好的SQL语句