首先,我正在使用jTextFields阅读用户的产品名称和产品数量.对于该产品,我使用SQL查询从数据库中读取产品ID和价格.但是在下面的代码中我在jtextField中显示产品价格,但是在运行tha文件时,我成功执行了查询,但是我没有在jtextField中获得任何内容.
请检查SQL查询和结果集使用,
表名是“item”,数据库名是“myshop”,
我全局声明变量,这段代码在jButton的’ActionPeformed’部分.
String item_name=name.getText(); int item_no=Integer.parseInt(no.getText()); String sql="SELECT id,price FROM item WHERE item.name='item_name'"; try{ Class.forName("com.MysqL.jdbc.Driver"); Connection con(Connection)DriverManager.getConnection("jdbc:MysqL://localhost:3306/myshop","root","MysqL"); java.sql.Statement stmt=con.createStatement(); if (stmt.execute(sql)) { rs = stmt.getResultSet(); JOptionPane.showMessageDialog(this,"succes","executed query",JOptionPane.PLAIN_MESSAGE); } else { System.err.println("select Failed");} int idindex = rs.findColumn("id"); int priceIndex = rs.findColumn("price"); while(rs.next()){ item_id=rs.getInt(idindex); item_price=rs.getInt(priceIndex); jTextField1.setText(""+item_price);//displaying product price in a jTextField1 jTextField2.setText(""+item_id);//displaying product id in a jTextField2 } } catch(Exception e){ JOptionPane.showMessageDialog(this,e.getMessage()); }
解决方法
你需要将item_name作为参数并放入引号,
String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";