简体   繁体   English

通过使用带有 SQL WHERE 子句的 Java 变量从结果集中获取主键值

[英]Getting primary key value from resultset by using Java variable with SQL WHERE clause

I know its not great practise at all to use techniques like this as it is prone to SQL injections, but for speed and testing this is currently how I am doing it.我知道使用这样的技术根本不是很好的做法,因为它很容易进行 SQL 次注入,但为了速度和测试,我目前正在这样做。 I am creating a program which saves a username, ip and a database name to another database.我正在创建一个程序,它将用户名 ip 和数据库名称保存到另一个数据库。 However when I try and perform a statement like so:但是,当我尝试执行这样的语句时:

ResultSet rs = stmt.executeQuery("SELECT LoginID, IPAddress FROM slavelogins WHERE IPAddress = '" + inputString + "';");
            String ClientID = String.valueOf(rs.getInt(1));
            System.out.println("Client ID: " + ClientID);
        } catch (SQLException err) {
            System.err.println("Error retrieving client id, please continue later!" + err);
            System.exit(0);

I then run into an error which says the value is before the start of resultset, I believe this means there is no data retrieved from the database, is there a way to fix this or a way around this or an easier way which I am not realising?然后我遇到一个错误,它说该值在结果集开始之前,我相信这意味着没有从数据库中检索到数据,有没有办法解决这个问题或解决这个问题的方法或我没有的更简单的方法意识到?

PS LoginID is a primary key if that creates any problems. PS LoginID 是主键,如果这会产生任何问题。

The code above retrieves the loginid and displays it to the user as 'ClientID: ' + rs.getInt(1) where rs.getInt should be the loginID.上面的代码检索 loginid 并将其显示为 'ClientID: ' + rs.getInt(1),其中 rs.getInt 应该是 loginID。

I have also seen posts about using placeholders in preparedstatements but I haven't seen anything regarding a select query in a normal statement.我也看到过关于在准备语句中使用占位符的帖子,但我还没有看到任何关于 select 查询的普通语句。

The error message:错误信息:

Error retrieving client id, please continue later.检索客户端 ID 时出错,请稍后继续。 java.sql:SQLException: Before start of result set java.sql:SQLException:结果集开始前

You can think of the ResultSet as a cursor over the rows you've queried.您可以将ResultSet视为已查询行的 cursor。 Whatever its position may be, you can use next() to check if there's another row there, and move the cursor to it.无论它的 position 是什么,您都可以使用next()检查那里是否还有另一行,并将 cursor 移动到它。

The first row of the result is no different - a ResultSet start before the first row , and you need to use next() to move to that row:结果的第一行没有什么不同 - ResultSet在第一行之前开始,您需要使用next()移动到该行:

if (rs.next()) {
    String clientID = String.valueOf(rs.getInt(1));
    System.out.println("Client ID: " + clientID);
} else {
    System.out.println("No such client");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM