首先,我使用 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());
}
最佳答案
这一行应该是
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
像这样
String sql="SELECT id,price FROM item WHERE item.name='"+item_name+"'";
关于java - 使用java从mysql数据库中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626886/