【问题标题】:Getting Primary key from mysql by given name parameter in Java通过Java中的给定名称参数从mysql获取主键
【发布时间】:2015-07-03 16:41:39
【问题描述】:

我的 java 代码出现异常。我想从给定的名称中获取 Id,在这种情况下 Id 是主键。当我在工作台中查询时,Mysql 查询有效:

SELECT client_id FROM client where concat(lastname, " ", firstname) = "Hudson Kate";

但是当我在 javacode 中使用这个查询时:

public int getClientID(String name) throws SQLException{
        int ID = 0;
        PreparedStatement myprepStmt = null;
        ResultSet myRs = null;

        try {
            myprepStmt = myConn.prepareStatement("SELECT client_id FROM client "
                    + "where concat(lastname, \" \", firstname) =?");

            myprepStmt.setString(1, name);
            myRs = myprepStmt.executeQuery();

            ID = myRs.getInt("client_id"); //this creates a problem

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally {
            close(myprepStmt, myRs);
        }

        return ID;
    }

我得到了这个例外:

java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:787)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2460)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2571)
at DBConnection.getClientID(DBConnection.java:135)
at sample.main(sample.java:38)

【问题讨论】:

    标签: java jdbc


    【解决方案1】:

    你忘了用ResultSet#next

    myRs = myprepStmt.executeQuery();
    if (myRS.next()) { //<-- IMPORTANT!
        ID = myRs.getInt("client_id");
    }
    

    这里解释了ResultSet#next 的工作原理:ResultSet.getString(1) throws java.sql.SQLException: Invalid operation at current cursor position

    【讨论】:

    • 感谢您的回答。我忘记了 ResulSet next()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多