Skip to content
Advertisement

Reading data from mysql database using java

Firstly, I’m reading the product name and number of products from user using jTextFields. For that product I read the product id and price from database using sql query. But in the below code I display the product price in a jtextField but while running tha file I get query executed successfully but I’m not getting anything in the jtextField.

And please check the sql query and resultset use, table name is “item” and database name is “myshop”, I declared variables globelly and this code is in a jButton’s ‘ActionPeformed” part.

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

Advertisement

Answer

you would need to take item_name as param and put in quotes,

String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement