报错java.sql.SQLException: Before start of result set的解决

public class Testmysql {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://ip:3307/数据库名?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
    static final String USER ="";
    static final String PASS ="";
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT *FROM ambulance WHERE device_id='testdeviceid450'";
            ResultSet rs = stmt.executeQuery(sql);
            rs.next();//加了这行就可以了
            String device_id  = rs.getString("device_id");

使用rs.getString();前一定要加上rs.next();

原因:虽然sql语句已经准确查到了某一条数据,但是ResultSet 对象是一个结果集,最开始的光标是在最上面,也就是第一行上面,所以需要用.next()将光标移动到第一行才能继续取数据

你可能感兴趣的:(java,java,mysql)