这是我的 Index.java
String value1;
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1=textField.getText();
String Cusname = null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionURL = "jdbc:sqlserver://ROHAN\\SQLEXPRESS;Database=sys;user=rohan;password=rurouni;";
Connection con = DriverManager.getConnection(connectionURL);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select Name from loyaltycard where LCnum='"+value1+"'");
int count=0;
while(rs.next()){
count++;
Cusname = rs.getString("Name");
}
if(value1.equals("")) {
JOptionPane.showMessageDialog(null,"Enter Loyalty Card Number","Error",JOptionPane.ERROR_MESSAGE);
}
else if(count>0){
JOptionPane.showMessageDialog(null,"Login Successful \n"+Name,"Welcome",JOptionPane.PLAIN_MESSAGE);
new myitems().setVisible(true);
setVisible(false);
}
else{
textField.setText("");
JOptionPane.showMessageDialog(null,"Invalid Loyalty Card Number","Error",JOptionPane.ERROR_MESSAGE);
}}
catch(Exception e1){e1.printStackTrace();}
}
});
}
public String getVal()
{
return value1;
}
}
这是我的 checkout.java
index LCval = new index();
final String LCnum = LCval.getVal();
JButton btnNewButton_1 = new JButton("Finish");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
int bal = 0;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionURL = "jdbc:sqlserver://ROHAN\\SQLEXPRESS;Database=sys;user=rohan;password=rurouni;";
Connection con = DriverManager.getConnection(connectionURL);
PreparedStatement pst =null;
ResultSet rs = null;
//Statement st=con.createStatement();
String sql="Select Balance From loyaltycard where LCnum='"+LCnum+"' ";
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
bal = rs.getInt("Balance");
JOptionPane.showMessageDialog(null,"Payment Successful!\n Your current balance is:"+bal,"Client",JOptionPane.INFORMATION_MESSAGE);
new index().setVisible(true);
setVisible(false);
}
}
catch(Exception e1){e1.printStackTrace();}
}});
我想将index.java的文本字段中输入的值获取到checkout.java 当我按下 checkout.java 上的按钮时,出现此错误。
com.microsoft.sqlserver.jdbc.SQLServerException:将 varchar 值“null”转换为数据类型 int 时转换失败。
最佳答案
SQL Server 返回您不在代码中处理的 NULL
值。
在这种情况下,一种方法可能是返回零而不是 null:
String sql="Select isnull(Balance,0) as Balance From loyaltycard where LCnum='"+LCnum+"' ";
顺便说一句,不要连接你的查询,这会让你容易受到 SQL 注入(inject)的攻击。请改用参数。
更新:
根据讨论,还有更多问题:
由于LCnum
列的类型为int
,因此查询中的where
子句应不带引号字符:
"... where LCnum="+value1
关于java - 获取从一个类到另一个类的文本字段中输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20727331/