[英]Searching a integer type database field through java
我想通過提供一個憑證號碼作為搜索條件來搜索數據庫,但保證號碼是整數,所以我不能用以下代碼執行此操作,請為此建議一些其他代碼。
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);
}
使用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 = ?";
您的代碼中有一個簡單的錯誤(“其中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()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.