2012-07-10 78 views
0

我試圖做一個搜索程序:前端 - java和後端 - mysql。mySql-java簡單的搜索控制檯應用程序

我試着一點點,下面的代碼:

public static void searchRecord() throws SQLException{ 

    Scanner in = new Scanner(System.in); 
    int empnum; 

    System.out.print("Enter employee number: "); 
    empnum = in.nextInt(); 

    String search = "SELECT fname FROM employees WHERE emp_num='"+ empnum + "'"; 
     resultSet = statement.executeQuery(search); 

    String empnum_rs = null;  

    while(resultSet.next()){ 
     empnum_rs = resultSet.getString(empnum); 



    } 

    System.out.print(empnum_rs); 
} 

我來到這裏的問題是,當我鍵入emp_num日食拋出這些行:

Exception in thread "main" java.sql.SQLException: Column Index out of range, 2 > 1. 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919) 
    at com.mysql.jdbc.ResultSetImpl.checkColumnBounds(ResultSetImpl.java:830) 
    at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5773) 
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5692) 
    at Test.searchRecord(Test.java:55) 
    at Test.main(Test.java:37) 

回答

2

getXXX...函數的列號從1開始到n,其中n是查詢中選擇的最大列數。您的查詢只有一列被選中。而empnum可能不等於1,因此會引發錯誤。

變化:

empnum_rs = resultSet.getString(empnum); 

到:

empnum_rs = resultSet.getString(1); 
+0

哦感謝隊友!我應該爲我的emp_num放置列。再次感謝 – 2012-07-10 13:29:20

+0

您可以在'get ...'方法中使用coumn編號或列名稱。 – 2012-07-10 13:30:32

+0

但是當我添加lname列時,它只顯示fname。我如何連接姓氏? – 2012-07-10 13:30:38

相關問題