加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:16:21 所属栏目:Java 来源:网络整理
导读:首先,我正在使用jTextFields阅读用户的产品名称和产品数量.对于该产品,我使用sql查询从数据库中读取产品ID和价格.但是在下面的代码中我在jtextField中显示产品价格,但是在运行tha文件时,我成功执行了查询,但是我没有在jtextField中获得任何内容. 请检查sql查
首先,我正在使用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+"'";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读