我想通过提供凭证编号作为搜索条件来搜索数据库,但是保证号是整数,所以我不能使用以下代码执行此操作,请为此建议一些其他代码。
try{
String sql = "select item_type as 'Item Type', md_by as 'Made By', model as 'Model', selling_price as 'Selling Price', purchase_price as 'Purchase Price', purchase_date as 'Purchase Date', vouch_no as 'Voucher No.', vouch_date as 'Voucher Date', record_no as 'Record No.' from purchase" where vouch_no = ?;
ps = con.prepareStatement(sql);
ps.setString(1 , txt_vouchno_p.getText());
rs = ps.executeQuery();
Table_p.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null, "Error: " + ex);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Error: " + ex);
}
答案 0 :(得分:3)
使用Integer#parseInt
将txt_vouchno_p.getText()
的值转换为int
并相应地将其传递给PreparedStatement
:
ps.setInt(1, Integer.parseInt(txt_vouchno_p.getText()));
在您当前的代码中看起来像是一个拼写错误,但是对于大文字String
,不要害怕将它拆分成几行,编译器足够智能将其转换为单个大String
} 为了你。所以,这一行:
String sql = "select item_type as 'Item Type', md_by as 'Made By', model as 'Model', selling_price as 'Selling Price', purchase_price as 'Purchase Price', purchase_date as 'Purchase Date', vouch_no as 'Voucher No.', vouch_date as 'Voucher Date', record_no as 'Record No.' from purchase" where vouch_no = ?;
应改写为:
String sql = "select item_type as 'Item Type'"
+ ", md_by as 'Made By'"
+ ", model as 'Model'"
+ ", selling_price as 'Selling Price'"
+ ", purchase_price as 'Purchase Price'"
+ ", purchase_date as 'Purchase Date'"
+ ", vouch_no as 'Voucher No.'"
+ ", vouch_date as 'Voucher Date'"
+ ", record_no as 'Record No.'"
+ " from purchase"
+ " where vouch_no = ?";
答案 1 :(得分:0)
你的代码中有一个简单的错误(“vouch_no ...”不在字符串sql中),它应该是:
String sql = "select item_type as 'Item Type', md_by as 'Made By', model as 'Model', selling_price as 'Selling Price', purchase_price as 'Purchase Price', purchase_date as 'Purchase Date', vouch_no as 'Voucher No.', vouch_date as 'Voucher Date', record_no as 'Record No.' from purchase where vouch_no = ?";
您可以像这样设置参数:
ps = con.prepareStatement(sql);
ps.setString(1 , Integer.parseInt(txt_vouchno_p.getText()));