在preparedStatement中编辑查询

时间:2014-09-18 01:38:05

标签: java sql database jdbc edit

是否可以编辑之前在另一个方法中使用过的preparedStatement? 例如:

public class MyDB {
private Connection c;
private PreparedStatement p;

public void foo() {
    // connecting to DB...try-catch-block...
    p = c.prepareStatement("SELECT * FROM t WHERE NAME=?");
    p.setString(1, "Tom");

}

public void boo(){
    // connecting to DB...try-catch-block...        
    //Here I want to concat the query with something
    --> p = ....." AND City=?";
    p.setString(2, "London");

    ResultSet rs = p.executeQuery();
    [...]


}
}

1 个答案:

答案 0 :(得分:0)

简短回答:。答案很长:不是真的,而且你似乎没有正确使用PreparedStatement。你可以做类似的事情 -

private String query = "SELECT * FROM t WHERE NAME=?";
public void foo() {
    // connecting to DB...try-catch-block...
    ResultSet rs = null;
    try (PreparedStatement ps = c.prepareStatement(query);) {
        ps.setString(1, "Tom");
        rs = ps.executeQuery();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public void boo() {
    // connecting to DB...try-catch-block...
    // Here I want to concat the query with something
    String sql = query + " AND City=?";
    ResultSet rs = null;
    try (PreparedStatement ps = c.prepareStatement(sql);) {
        ps.setString(1, "Tom");
        ps.setString(2, "London");
        rs = ps.executeQuery();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}