MySQL + JAVA 异常:在结果集开始之前
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2260575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL + JAVA Exception: Before start of result set
提问by user272695
try
{
PreparedStatement s = (PreparedStatement) conn.prepareStatement("SELECT voters.Check,count(*) FROM voting.voters where FirstName="+first+"and LastName="+last+" and SSN="+voter_ID);
//java.sql.Statement k = conn.createStatement();
rs=s.executeQuery();
//s.executeQuery("SELECT voters.Check,count(*) FROM voting.voters where FirstName="+first+"and LastName="+last+" and SSN="+voter_ID);
System.out.println(rs.first());
c=rs.getInt(1);
d=rs.getInt(2);
System.out.println(c);
System.out.println(d);
if(c==1 && d==1)
{
s.executeUpdate("update cand set total=total+1 where ssn="+can_ID);
System.out.println("Succeful vote");
System.out.println("after vote");
s.executeUpdate("update voters set voters.Check=1 where ssn="+voter_ID);
toclient=1;
PreparedStatement qw = (PreparedStatement) conn.prepareStatement("select FirstName from cand where ssn="+can_ID);
// rs=k.executeQuery("select FirstName from cand where ssn="+can_ID);
rs1 = qw.executeQuery();//Error Here Plz help me
String name1= (String) rs1.getString(1);
System.out.println(name1);
s.executeUpdate("update voters set VTO="+name1+"where ssn="+voter_ID);
System.out.println(rs.getString(1));
}
else
{
if(c != -1)
toclient =2;
if( d ==0)
toclient =3;
if( d>1)
toclient =4;
}
System.out.println("out-----------");
rs.close();
s.close();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error IS :
错误是:
java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1072)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:986)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:981)
回答by nanda
While rs1.first()may work, to avoid exception I would like to avoid it and use rs1.next()instead.
虽然rs1.first()可能有效,但为了避免异常,我想避免它并使用它rs1.next()。
See javadoc of ResultSet.first():
请参阅以下的 javadoc ResultSet.first():
SQLException - if a database access error occurs; this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
SQLException - 如果发生数据库访问错误;在关闭的结果集或结果集类型为 TYPE_FORWARD_ONLY上调用此方法
SQLFeatureNotSupportedException -如果 JDBC 驱动程序不支持此方法
while nextdoesn't have this limitation
whilenext没有这个限制
Code:
代码:
if (rs1.next()) {
String name1 = rs1.getString(1);
}
Tips: avoid useless type casting (your code is full of them)
提示:避免无用的类型转换(你的代码充满了它们)
回答by incarnate
The common practice is to use rs.next()method with whilecycle:
通常的做法是使用rs.next()带有while循环的方法:
PreparedStatement st = conn.prepareStatement("select 1 from mytable");
ResultSet rs = st.executeQuery();
while (rs.next()) {
// do something with result set
}
rs.close();
st.close();
I've omitted try/catch/finally clauses for clarity. Note that you should invoke each close()method in separate finallyblock.
为清楚起见,我省略了 try/catch/finally 子句。请注意,您应该close()在单独的finally块中调用每个方法。
回答by futureelite7
When you get a resultset, the cursor is placed before the first row. Trying to get anything before moving your cursor to the first row will cause the error you received. You need to move the cursor to the first row using this line:
当您获得结果集时,光标将放置在第一行之前。在将光标移动到第一行之前尝试获取任何内容将导致您收到错误。您需要使用以下行将光标移动到第一行:
rs1.first();
before calling
打电话之前
String name1 = (String) rs1.getString(1);
Of course, make sure the resultset contains entries before calling rs1.getString(1).
当然,在调用 rs1.getString(1) 之前,请确保结果集包含条目。
回答by rsp
In your code snippet you create PreparedStatements but you do not use them correctly. Prepared statements are meant to be used as a kind of 'statement template' which is bound to values before it executes. To quote the javadoc:
在您的代码片段中,您创建了 PreparedStatements 但您没有正确使用它们。准备好的语句旨在用作一种“语句模板”,它在执行之前绑定到值。引用 javadoc:
PreparedStatement pstmt = con.prepareStatement(
"UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
This has two big advantages over your current usage of PreparedStatement:
与您当前使用 PreparedStatement 相比,这有两大优势:
- one PreparedStatement can be used for multiple executes
- it preventsa possible SQL injectionattack
- 一个 PreparedStatement 可用于多次执行
- 它可以防止可能的SQL 注入攻击
The second one here is the biggie, if for instance your variables firstand lastare collected in a user interface and not reformatted, you run the risk of parts of SQL being input for those values, which then end up in your statements! Using bound parameters they will just be used as values, not part of the SQL statement.
这里的第二个是大不了的,举例来说如果你的变量first,并last收集在一个用户界面,而不是重新格式化,您运行这些值SQL是输入部分的风险,这在随后的发言结束了!使用绑定参数,它们将仅用作值,而不是 SQL 语句的一部分。
回答by Bozho
Call rs1.first()before using the ResultSet.
rs1.first()使用前调用ResultSet。
Moves the cursor to the first row in this ResultSet object.
将光标移动到此 ResultSet 对象中的第一行。
Initially the cursor position of the ResultSetis before the start of the set. The first()method returns trueif there is data in the set. So preferably:
最初的光标位置ResultSet在集合的开始之前。如果集合中有数据,则该first()方法返回true。所以最好:
if (rs1.first()) {
String name1 = (String) rs1.getString(1);
}
回答by Piko
So, to be sure the proper use of PreparedStatment, here is your original example adjusted for best practices (note the cast is redundant):
因此,为了确保正确使用 PreparedStatment,以下是针对最佳实践进行调整的原始示例(注意演员表是多余的):
PreparedStatement s = conn.prepareStatement(
"SELECT voters.Check,count(*) " +
"FROM voting.voters " +
"where FirstName=? and LastName=? and SSN=?");
s.setString(1,first);
s.setString(2,last);
s.setString(3,voter_ID);
ResultSet rs = s.executeQuery();
while( rs.next() ) {
c = rs.getInt(1);
d = rs.getInt(2);
}
Hope this helps... :)
希望这可以帮助... :)

