我尝试从数据库中获取一些数据.连接方法确实有效,但我在获取任何数据表单DB时遇到问题:
SQLConnect s = new SQLConnect();
Connection c = s.getConnection();
Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select * from produkty");
System.out.println(rs.getString(2));
Run Code Online (Sandbox Code Playgroud)
问题出在最后一行(当我评论它时,没有出现错误).错误信息:
Connected to database
Exception in thread "main" java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:841)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5656)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5576)
at antmedic.Main.main(Main.java:85)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
您需要调用ResultSet#next()将结果集游标移动到下一行.通常,当有多行的方法时,请在while循环中执行此操作.
while (rs.next()) {
System.out.println(rs.getString(2));
}
Run Code Online (Sandbox Code Playgroud)
或者当您期望零行或一行时,请使用if语句.
if (rs.next()) {
System.out.println(rs.getString(2));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13617 次 |
| 最近记录: |