Using java to read data from MySQL database

First, I'm using jtextfields to read the user's product name and product quantity For this product, I use SQL query to read the product ID and price from the database But in the following code, I display the product price in jtextfield, but when I run the tha file, I successfully execute the query, but I don't get anything in jtextfield

Please check the use of SQL query and result set. The table name is "item", the database name is "myshop", and I declare variables globally. This code is in the 'actionformed' part of JButton

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());
}

Solution

You need to add item_ Name as a parameter and in quotation marks,

String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>