简体   繁体   English

如何在Swing中从JTextField获取作为整数的值?

[英]How to get value as integer from JTextField in swing?

Actually i'm using oracle jdbc type4 thin driver. 实际上,我正在使用oracle jdbc type4瘦驱动程序。 And I'm creating registration form in swing with eclipse with following columns pid,name,addrs. 我正在用下面的pid,name,addrs列用eclipse创建注册表单。 the problem is i'm getting only string value which method is ps.setString=(2,JTextfiled.getText()); 问题是我只得到字符串值,该方法是ps.setString=(2,JTextfiled.getText()); but i'm not able get int value like ps.setInt(1.getxxx()); 但是我无法获得像ps.setInt(1.getxxx());这样的int值ps.setInt(1.getxxx()); can anyone guide me how to insert int value to database. 谁能指导我如何将int值插入数据库。

//prepare query
String query1 ="insert into employee values(?,?,?,?,?)";
//create preapare Statement
ps = con.prepareStatement(query1);
//set params
ps.setString(1,textField.getText());
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
ps.setString(4,textField_3.getText());
ps.setString(5, textField_4.getText());
//execute query
int count = ps.executeUpdate();
if(count==0)
{
    JOptionPane.showMessageDialog(null, "Record not Inserted");
}
else
{
    JOptionPane.showMessageDialog(null, "Record inserted into database successfuly");
}

Use Integer.parseInt to convert your string to an int , then use PreparedStatement#setInt to set it on the statement for insertion. 使用Integer.parseInt将您的字符串转换为int ,然后使用PreparedStatement#setInt在要插入的语句上设置它。 Eg: 例如:

ps.setInt(1, Integer.parseInt(textField.getText()));

You'll want to catch NumberFormatException in case the values in the text fields are not valid integers. 如果文本字段中的值不是有效的整数,则需要捕获NumberFormatException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM