简体   繁体   English

在SQL查询中使用组合框的值

[英]Use the value of a combo box in a SQL query

How can I use the value of a combo box in a SQL query with Java? 如何使用Java在SQL查询中使用组合框的值? I try this code but it doesn't work. 我尝试了此代码,但是它不起作用。

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

If I use this code, it works. 如果我使用此代码,它将起作用。

String sql = " select * from table1 where Name like ?";
    try{
        pst = conn.prepareStatement(sql);
        pst.setString(1, txtsearch.getText() + "%");
        rs = pst.executeQuery();}

Well, you can do something like this: 好吧,您可以执行以下操作:

try {
    String sql = "select * from table1 where ";
    sql += (String) jComboBox2.getSelectedItem();
    sql += " like ";
    sql += txtsearch.getText() + "%";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
}

The place holder (?) is actually designed for the column values not for column/table name. 占位符(?)实际上是为列值而不是列/表名设计的。 Make use of string concatenation: 利用字符串串联:

String sql = "select * from table1 where "
                                  + jComboBox2.getSelectedItem()
                                  +" like ?";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM