如何在Java查询中使用组合框的值? 我尝试使用此代码,但它不起作用。
String sql = " select * from table1 where ? like ?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, (String) jComboBox2.getSelectedItem());
pst.setString(2, txtsearch.getText() + "%");
rs = pst.executeQuery();}
如果我使用此代码,它可以工作。
String sql = " select * from table1 where Name like ?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtsearch.getText() + "%");
rs = pst.executeQuery();}
答案 0 :(得分:1)
嗯,你可以这样做:
try {
String sql = "select * from table1 where ";
sql += (String) jComboBox2.getSelectedItem();
sql += " like ";
sql += txtsearch.getText() + "%";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
}
答案 1 :(得分:0)
占位符(?)实际上是为列值而不是列/表名设计的。使用字符串连接:
String sql = "select * from table1 where "
+ jComboBox2.getSelectedItem()
+" like ?";