当创建随机电子邮件并将其存储在 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 + "')");
这解决了问题,因为当您执行 UPDATE(第二个查询)时,来自 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);
}
关于java循环存储数据库并回调错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45210924/