[英]Prepared statement in if else
我正試圖在if else中使用預准備語句。 可悲的是,我得到的索引1超出了范圍。 添加了一些細節...我的代碼:
try {
String query = "select * from dbo.Table";
String width = jFormattedTextField1.getText();
String heigth = jFormattedTextField2.getText();
PreparedStatement ps;
if (width.equals("") && heigth.equals("")) {
query = "select * from dbo.Table ";
} else if (width != null && !"".equals(width) && heigth != null && !"".equals(heigth)) {
query += "where width = ? and heigth = ?";
ps = conn.prepareStatement(query);
ps.setString(1, width);
ps.setString(2, heigth);
} else if (width != null && heigth.equals("")){
query += "where width = " + width;
ps = conn.prepareStatement(query);
} else {
query += "where heigth = " + heigth;
ps = conn.prepareStatement(query);
}
ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "ERROR", JOptionPane.ERROR_MESSAGE);
}
初始化SQL String
后,您應該創建PreparedStatement
,這意味着它必須在if-else主體內完成。
String width = jFormattedTextField1.getText();
String heigth = jFormattedTextField2.getText();
PreparedStatement ps;
if (width.equals("") && heigth.equals("")) {
query = "select * from dbo.Table ";
ps = conn.prepareStatement(query);
} else if (width != null && !"".equals(width) && heigth != null && !"".equals(heigth)) {
query = "select * from dbo.Table where width = ? and heigth = ?";
ps = conn.prepareStatement(query);
ps.setString(1, width);
ps.setString(2, heigth);
}
您還應該在else
子句中初始化PreparedStatement
,以確保在執行它之前初始化它。
編輯:
查看更新的代碼,您在最后兩種情況下濫用PreparedStatement
。 我建議:
try {
String query = "select * from dbo.Table";
String width = jFormattedTextField1.getText();
String height = jFormattedTextField2.getText();
PreparedStatement ps;
if (width.equals("") && height.equals("")) {
ps = conn.prepareStatement(query);
} else if (width != null && !"".equals(width) && height != null && !"".equals(height)) {
query += " where width = ? and height = ?";
ps = conn.prepareStatement(query);
ps.setString(1, width);
ps.setString(2, height);
} else if (width != null && height.equals("")){
query += " where width = ?";
ps = conn.prepareStatement(query);
ps.setString(1, width);
} else {
query += " where height = ?";
ps = conn.prepareStatement(query);
ps.setString(1, height);
}
ResultSet rs = ps.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "ERROR", JOptionPane.ERROR_MESSAGE);
}
初始化SQL字符串后創建預准備語句。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.