2014-04-21 82 views
1

我想通過給出一個憑證號碼作爲搜索條件來搜索數據庫,但是證實號碼是整數,所以我不能用下面的代碼來做到這一點,請爲此建議一些其他代碼。通過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); 
     } 

回答

3

轉換的txt_vouchno_p.getText()價值爲int使用Integer#parseInt,並相應傳遞到您的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 = ?"; 
+0

我試圖解析,但仍然有錯誤。我試圖解析爲浮動,但沒有工作。 – Rehan

+0

@ user3248599請編輯您的問題併發布錯誤的堆棧跟蹤。另外,確保'txt_vouchno_p.getText()'的內容可以轉換爲'int'。 –

+0

好的。將發佈堆棧跟蹤。謝謝。 – Rehan

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()));