Java 如何在swing用户界面中将整数数据从数据库带到JTextField
我尝试制作一个swing用户界面组件,它有两个TextField,其中一个取产品名称,返回数据库中产品的价格。 代码中有一些错误,请参考一些解决方案。 代码如下:Java 如何在swing用户界面中将整数数据从数据库带到JTextField,java,mysql,swing,jdbc,Java,Mysql,Swing,Jdbc,我尝试制作一个swing用户界面组件,它有两个TextField,其中一个取产品名称,返回数据库中产品的价格。 代码中有一些错误,请参考一些解决方案。 代码如下: class Swingui implements ActionListener { JFrame jf=new JFrame("PRODUCT DETAILS"); JLabel jl1=new JLabel("Product:"); JTextField jtf1=ne
class Swingui implements ActionListener
{
JFrame jf=new JFrame("PRODUCT DETAILS");
JLabel jl1=new JLabel("Product:");
JTextField jtf1=new JTextField();
JTextField jtf2=new JTextField();
JLabel jl2=new JLabel("Price:");
JButton jb=new JButton("enter");
Swingui()
{
jf.setSize(500,500);
jf.setVisible(true);
jf.setLayout(null);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jl1.setBounds(50,70,100,30);
jf.add(jl1);
jtf1.setBounds(50,100,100,30);
jf.add(jtf1);
jl2.setBounds(50,150,100,30);
jf.add(jl2);
jb.setBounds(50,250,100,30);
jf.add(jb);
jtf2.setBounds(50,200,100,30);
jf.add(jtf2);
jb.addActionListener(this);
}
public static void main(String arg[])
{
new Swingui();
}
public void actionPerformed(ActionEvent ae){
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost/product";
Connection con=DriverManager.getConnection(url,"root","");
/*error*/Statement stmt=con.createStatement();
String qry="select price from price where good='"+jtf1.getText().toString()+"'";
/*error*/ResultSet resultSet= stmt.executeQuery(qry);
int price = resultSet.getInt("price");
JLabel jl3=new JLabel();
String str;
str=String.valueOf(price);
jl3.setText(str);
jl3.setBounds(50,300,100,50);
jf.add(jl3);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
MySQL数据库详细信息如下:
database: product
table : price
columns are
good price
==============
gold10gm 35000
dollar 78
在URL中添加本地主机端口号。resultSet将光标保留到当前获取的数据行。最初,光标将指向当前行之前,因此无法直接从结果集中获取结果。在访问值之前,尝试迭代它
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
rs.getInt("price");
您可以尝试使用preparedStatement而不是sql语句,以便稍后插入字符串的值。预期结果是什么?错误是什么?我希望你检查下面的答案。
String qry="select * from price where good= ? ";
PreparedStatement stmt=con.prepareStatement(qry);
stmt.SetString(jtf1.getText().toString);
stmt.execute();
ResultSet resultSet= stmt.getResultSet();
while (resultSet.next()) {
int price = resultSet.getInt("price");
}
JLabel jl3=new JLabel();
String str;
str=Integer.toString(price);
jl3.setText(str);
stmt.close(); // close the prepare statement if you don't need it further