简体   繁体   中英

how i can search in database using jTextField

hi every one i have write program that connect to database i create jTextField and jTable my question is how i can use the jTextField to serch in database and view in jTable the code i try is below

try{

    String host = "jdbc:derby://localhost:1527/PROCAT";
    String uName = "zain";
    String uPass = "zain";
    Connection con = DriverManager.getConnection( host, uName, uPass);
  String sql = "Select * from ITEMB where ITEM '"+asdf.getText()+"'";
   stmt = con.createStatement();

rs = stmt.executeQuery(sql);

  while (rs.next()) {
    String pr = rs.getString("PRISE");
    String it= rs.getString("ITEMNAME");
    String itm = rs.getString("ITEM");
    String[] data = {pr, it, itm};
    tabMode.addRow(data);
    double price = Double.parseDouble(rs.getString("prise"));
             totalpay = price + totalpay;
            ++rowCount;
  }
}
catch (Exception e) {
    //ignore
    }

    jTextField3.setText(String.valueOf(totalpay));






}            

Don't ignore the Exception. How to you expect to debug your SQL if you don't display error messages???

I would guess the problem is you are missing an "=" from your select statement (ie. "ITEM = asdf.getText()").

However, the better way to use SQL is to use a PreparedStatement so you don't have to worry about all the delimiters. So the SQL might be something like:

String sql = "Select * from ITEMB WHERE ITEM = ?";

PreparedStatement stmt = connection.prepareStatement(sql);

stmt.setString( 1, asdf.getText() );
stmt.executeQuery();
stmt.close();

It is much easier to read an maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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