我试图在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);
}
答案 0 :(得分:4)
初始化SQL PreparedStatement
后,您应该创建String
,这意味着它必须在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);
}
您还应该在PreparedStatement
子句中初始化else
,以确保在执行它之前对其进行了初始化。
编辑:
查看更新后的代码,您在最后两种情况下滥用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);
}
答案 1 :(得分:-1)
初始化SQL字符串后创建预准备语句。感谢