0

我正在使用选择查询按名称从表中选择特定记录。该表包含超过 25000 条记录。

表格格式为

|rcode|rname|vcode|vname|div_sec|ofrn|phone|dat|

此外,它可能包含多个具有相同名称的记录。我正在使用以下查询

ResultSet rs=stmt.executeQuery("select * from newfarmer where rname='"+get+"'");
if(rs.next())
{
     rcode=rs.getString("rcode");
     out.print(rcode);
     out.print(" ");
}

我必须找出给定 rname 的 rcode。现在使用上述查询的问题是,如果我搜索名称为“kannan”的记录,该表包含 6 个名称为“kannan”的记录

10001 kannan
10089 kannan
11826 kannan
12241 kannan
12389 kannan
19926 kannan

现在,我的查询只获取了第一条记录并给出结果为rcode="10001"

如果我使用

while(rs.next())
{
     rcode=rs.getString("rcode");
     out.print(rcode);
     out.print(" ");
}

它只会将最后一条记录打印为rcode="19926"。假设我想用 rcode 12241 获取“kannan”的记录,如何修改查询以获取记录?请注意,我必须只使用 rname 来获取详细信息。

这个问题有什么解决办法吗?请有人帮助我

4

2 回答 2

2

实际上,第二个片段应该输出所有记录,kannan除非你抄错了。将输出最后一个:

while(rs.next()) {
    rcode=rs.getString("rcode");
}
out.print(rcode);
out.print(" ");

理想的解决方案是根据两列将查询更改为限制:

select * from newfarmer where rname = 'kannan' and rcode = '12241'

但是,由于您认为这是一种可能性,因此您必须将它们全部获取并过滤出您想要的那些(但是与让 DBMS 这样做相比效率低下)。换句话说,类似:

while(rs.next()) {
    rcode=rs.getString("rcode");
    if (rcode == "12241") {       // or some other identifying condition.
        out.print(rcode);
        out.print(" ");
    }
}

我的建议是返回并重新检查您是否需要仅rname用于获取记录。这似乎是一个奇怪的限制,并且使任何解决方案都远不如其他解决方案那么理想。

于 2013-02-06T09:34:24.773 回答
1

The 2nd snipped would certainly retrieve all rows in the ResultSet, but be aware that there's no guaranteed order of the records unless you supply an order by clause in the SQL. Maybe that's why you think it's only getting the last - you're only looking at the first row returned, finding it's the id you expect last, and ignoring the rest. Just a possibility.

Is there an index on the rname column? If not, the query will be quite slow.

Also, this:

ResultSet rs=stmt.executeQuery("select * from newfarmer where rname='"+get+"'");

is a big, open invitation to SQL injection attacks. Insead use parameters in a prepared statement:

//Just prepare the statement once for multiple uses:
Statement stmt = conn.prepareStatement("select * from newfarmer where rname=?");

//use it:
stmt.setString(1, name);
ResultSet rs = stmt.execute(); 
// etc...
于 2013-02-06T09:47:37.360 回答