在使用JDBC查詢數據庫報了這么一個錯誤
CREATE TABLE `d_user` ( `id` int(10) NOT NULL, `name` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
insert into d_user values(1,'sean');
public class Test {
public static void main(String[] args){
Connection conn = null;
Statement stat = null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String pwd = "196428";
conn = DriverManager.getConnection(url, user, pwd);
stat = conn.createStatement();
String sql = "select name from d_user where id = 1";
ResultSet rs = stat.executeQuery(sql);
// if(rs.next()){
String name = rs.getString(1);
System.out.println(name);
// }
}catch(Exception e){
e.printStackTrace();
}finally{
if(null != conn){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != stat){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
運行結果為:
java.sql.SQLException: Before start of result set
具體的報錯信息和使用的數據庫驅動有關系,當我把數據庫驅動更換為mysql-connector-java-5.1.6-bin.jar后(原先使用的驅動為mysql-connector-java-5.1.10.jar),報錯為:
java.sql.SQLException at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
去掉測試代碼中的注釋部分后運行正常:
sean
在對結果集ResultSet進行操作之前,一定要先用ResultSet.next()將指針移動至結果集的第一行
看看API對next()方法的描述:
...... 將光標從當前位置向前移一行。ResultSet 光標最初位於第一行之前;第一次調用 next 方法使第一行成為當前行;第二次調用使第二行成為當前行,依此類推。 當調用 next 方法返回 false 時,光標位於最后一行的后面。 ......
JDBC寫起來讓人眼花
