mySql-java简单搜索控制台应用程序

时间:2012-07-10 13:25:32

标签: java mysql search

我正在尝试做一个搜索程序:前端 - java和后端 - mysql。

我尝试了一下,这是代码:

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 eclipse时会抛出这些行:

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)

1 个答案:

答案 0 :(得分:1)

getXXX...函数采用从1到n的列号,其中n是查询中选择的最大列数。您的查询只有一列可供选择。 empnum可能不等于1,因此会抛出错误。

更改:

empnum_rs = resultSet.getString(empnum);

到:

empnum_rs = resultSet.getString( 1 );