使用java从mysql数据库读取数据

首先,我正在使用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+"'";

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...