这是我的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时转换失败。
答案 0 :(得分:2)
SQL Server返回NULL
值,您在代码中未处理该值。
在这种情况下,一种方法可能是返回零而不是null:
String sql="Select isnull(Balance,0) as Balance From loyaltycard where LCnum='"+LCnum+"' ";
顺便说一句,不要连接你的查询,这使你容易受到SQL注入攻击。改为使用参数。
<强>更新强>
根据讨论,还有更多问题:
由于LCnum
列的类型为int
,查询中的where
子句应不带引号字符:
"... where LCnum="+value1
答案 1 :(得分:0)
我刚刚在公共字符串getVal()中添加了静态,它刚刚解决了问题