簡體   English   中英

比較整數文本字段值與Java中的mysql數據

[英]compare integer text field value with mysql data in java

我要檢查表中是否已經有新輸入的數據

碼:

txtNo   = new JTextField();
{
    try {
        Class.forName("com.mysql.jdbc.Driver");
        String srcurl1      = "jdbc:mysql://localhost:3306/DB_name"; 
        Connection con      = DriverManager.getConnection(srcurl1,"root","paswrd");
        Statement stmt1     = con.createStatement();
        ResultSet rs1       = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");

        int ch =rs1.getInt("No");
        int ch4= Integer.parseInt(txtNo.getText());

        if(ch==ch4)    // input 58 == 58
         System.out.println("already exits");
    }
    catch(Exception e)
    {
        System.out.println("Exception:"+e);
    }
}

錯誤: Exception:java.sql.SQLException: Illegal operation on empty result set.

您需要先檢查ResultSet才能檢查它是否包含行:

if (rs1.next()) {
   int ch =rs1.getInt("No");
   ...
}

當select語句返回一個空集時,您將獲得此異常。 添加一個try / catch塊,該塊將根據catch塊中表中尚未存在的數據來進行操作。

您需要檢查結果集是否包含元素:

while(rs1.next())
{
    int ch = rs1.getInt("No");
    // ...
}

檢查數據庫中是否存在特定記錄的最簡單方法如下:

Select 1 from bank where No = [your_supplied_value]

如果查詢在數據庫中找到包含所提供數據的行,則該查詢將返回1或返回空結果集。 因此,您需要檢查的是結果集中是否返回了ANY值,或者它是否為空值。

這是一個示例代碼,可以幫助您入門:

txtNo   = new JTextField();
{
    try {
        String compareText = txtNo.getText().trim();

        if(compareText.length() > 0){
            Class.forName("com.mysql.jdbc.Driver");
            String srcurl1      = "jdbc:mysql://localhost:3306/DB_name"; 
            Connection con      = DriverManager.getConnection(srcurl1,"root","paswrd");
            Statement stmt1     = con.createStatement();
            ResultSet rs1       = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");

            boolean isPresent = rs1.next();

            if(isPresent){
                System.out.println("Already exists!!");
            }
        }
    }
    catch(Exception e)
    {
        System.out.println("Exception:"+e);
    }
}

我希望這不是您的最終代碼,因為存在一些問題:

  • 您沒有正確管理資源。 查詢完數據庫后,應考慮關閉結果集,語句和連接對象。

  • 請注意,我檢查了JTextField中的文本是否為空。 當您知道文本字段中沒有任何值時,這是防止調用數據庫的好方法。

  • 我建議使用PreparedStatement而不是Statement來查詢數據庫。

ResultSet最初位於第一行之前 因此,在調用getXXX()方法之一之前,需要調用next()將其移至下一行(並檢查它是否返回true )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM