java 循环存储数据库并回调错误

java loop store database and call it back error

当创建随机电子邮件并将其存储在 mysql 数据库中时,它工作正常,然后我尝试打印该随机电子邮件,但我不能。任何人帮助我在哪里可以编辑我的代码? 没有 ResultSet rs=statement.executeQuery("select * from user_data");System.out.println(rs.getString(1)); 工作正常
注意:- 有人请编辑我的语法

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Random;

public class new_test {

    public static void main(String[] args) {
    ArrayList<String>objectsToStores = new ArrayList<>();

        Random rad = new Random();

        for (int j=1; j<=3; j++ )
        {
            objectsToStores.add("usename"+rad.nextInt()+"@gmail.com");

        }

        try {

            Class.forName("com.mysql.jdbc.Driver") ;

            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "");

            connection.setAutoCommit(false);
            Statement statement = connection.createStatement();
            ResultSet rs=statement.executeQuery("select * from user_data");

            for (String x : objectsToStores  ) {

                statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" +x +"')");

            }

while(rs.next())

                System.out.println(rs.getString(1)); 

            connection.commit();
            statement.close();
            connection.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}

问题是您在数据库上执行查询时使用的顺序 我刚下线

ResultSet rs = statement.executeQuery("select * from user_data");

之后

statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x + "')");

这解决了问题,因为当您执行更新(第二个查询)时,结果集来自 SELECT 被语句关闭所以你不能迭代它,给你一个错误

try {
    // This is not needed anymore with the new driver
    //Class.forName("com.mysql.jdbc.Driver");

    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "");

    connection.setAutoCommit(false);
    Statement statement = connection.createStatement();

    for (String x : objectsToStores) {
        statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x + "')");
    }

    // I just moved this line down
    ResultSet rs = statement.executeQuery("select * from user_data");
    while (rs.next())
        System.out.println(rs.getString(1));

    connection.commit();
    statement.close();
    connection.close();

} catch (Exception e) {
    throw new RuntimeException(e);
}