java - 通过java搜索整数类型的数据库字段

标签 java jdbc

我想通过提供凭单编号作为搜索条件来搜索数据库,但凭单编号是整数,因此我无法使用以下代码执行此操作,请为此建议一些其他代码。

  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#parseInttxt_vouchno_p.getText() 的值转换为 int并将其相应地传递给您的 PreparedStatement:

ps.setInt(1, Integer.parseInt(txt_vouchno_p.getText()));

在你当前的代码中看起来像是一个拼写错误,但是对于大的文字 String,不要害怕将它分成几行,编译器足够聪明,可以将它转换成一个大的 code>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 = ?";

关于java - 通过java搜索整数类型的数据库字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23202609/

相关文章:

java - "does not include"的 JsonPath 语法,还是负匹配?

java - 创建一个 Applet Mad Libs 游戏

java - 如何懒惰地评估嵌套的 flatMap

java - SQLException : Operation not allowed after ResultSet closed error

java - 从 Array 到 hashMap 的值

java - 由 : org. springframework.data.mapping.PropertyReferenceException: No property findAll found for type User - Redis 引起

java - google-api-translate-java 检索翻译时出错

java - 找不到类 [org.apache.derby.jdbc.ClientDriver] 异常

java - 使用 CallableStatements 枚举作为针对 SQL 注入(inject)的白名单

java - 无法将 Java ap 连接到在线 MySQL 数据库 - 错误的 URL