微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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+"'";

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐