2014-08-30 60 views
0

你好我正在使用java和MySQL。我的實施如下:Java檢查數據庫中是否存在值

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import java.sql.*; 
import java.util.Scanner; 

public class BankingSystem extends JFrame { 
    public static void main(String[] args) throws Exception{ 
     int ur=0; 
     int PIN; 
     String ID; 
     Scanner s=new Scanner(System.in); 
     Class.forName("com.mysql.jdbc.Driver"); 
     String url = "jdbc:mysql://localhost:3306/BankingSystem"; 
     String user = "root"; 
     String pass=""; 
     Connection con = DriverManager.getConnection(url,user,pass); 
     Statement st = con.createStatement(); 
     System.out.println("Enter Your 4 digit PIN"); 
     PIN=s.nextInt(); 

     ResultSet rs=st.executeQuery("select * from customerinformation where pin ="+PIN); 
//checking for existance of user entered pin 
if((rs.getString(1)).equals("")){System.out.println("Invalid PIN");} 


     while(rs.next()) 
     { 

      System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)); 

     } 

    } 

} 

但這段代碼不起作用。給某種異常錯誤,但當我刪除包含if語句的行,那麼它工作正常。如何檢查引腳是否有效。

它給以下異常:

Exception in thread "main" java.sql.SQLException: Before start of result set 
     at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:3624) 
     at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1762) 
     at BankingSystem.main(BankingSystem.java:22) 
+0

您可以發佈異常的詳細信息? – 2014-08-30 13:56:54

回答

2

嘗試這種方式 替換該Statement st = con.createStatement();

String query ="select * from customerinformation where pin =?" 
PreparedStatement st =con.prepareStatement("query"); 
st.setInt(1,PIN); 
ResultSet resultSet = st.executeQuery(); 

你不應該使用在聲明PreparedStatement的

if (!resultSet.next()) { 
    System.out.println("resultset does not data"); 
} else { 

    do { 
     System.out.println(rs.getString(1)+" "+ 
          rs.getString(2)+" "+ 
          rs.getString(3)+" "+ 
          rs.getString(4)); 


    } while (resultSet.next()); 
} 
+0

謝謝!它的工作.... – AZT 2014-08-30 14:11:12

+0

+1用於推薦與綁定變量準備好的語句。 – Brandon 2014-08-30 14:11:47

0
if((rs.getString(1)).equals("")){ 
    System.out.println("Invalid PIN"); 
} 

沒有rs.next()rs.getString(1)是不可能

試試這個:

if(rs.next()){ 
     System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)); 
    } else { 
    System.out.println("Invalid PIN"); 
    } 
相關問題