2017-07-20 102 views
1

这里这是我的随机邮件生成器代码,我想保存随机邮件,我该怎么做?如何存储java循环输出?

public class stupit { 

public static void main(String[] args) { 
     Random randomGenerator = new Random(); 

    for (int i=1; i<=5; i++) 

    { 
     int randomInt = randomGenerator.nextInt(1000); 
     System.out.println("username"+randomInt+"@gmail.com"); 

    } 
    } 
    } 
out put is 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

如何保存这些放出来像A = [email protected][email protected] .....

+1

要保存它在哪里?在文件,数组,数据库等? –

+0

存储它在哪里?一个数据库?一个txt文件..? –

+0

@ScaryWombat它如何重复这个问题? –

回答

1

您需要为要在其中保存这些电子邮件的数据库添加其他驱动程序库。
您可以在maven central的数据库中找到jdbc驱动程序。

对于mysql数据库一般的代码可以是这样的:

ArrayList<String> objectsToStore = new ArrayList<>(); 
    Random rnd = new Random(); 

    for (int i = 1; i <= 5; i++) { 
     objectsToStore.add("username" + rnd.nextInt() + "@gmail.com"); 
    } 

    try { 
     //1) this used to load mysql jdbc driver into memory 
     Class.forName("com.mysql.jdbc.Driver"); 
     //2) create connection to running mysql instance 
     Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName?useSSL=false", "username", "password"); 
     connection.setAutoCommit(false); 
     Statement statement = connection.createStatement(); 
     for (String objectToStore : objectsToStore) { 
      // this insert will work assuming you have table user_data with email field 
      statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + objectToStore +"')"); 
     } 
     //commit transaction 
     connection.commit(); 
     statement.close(); 
     connection.close(); 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 

SQL在数据库中创建一个表:

create table User_data(
    email varchar(255) 
); 
+1

_Exception java.lang.Error:未解决的编译问题: \t Duplicate local variable objectsToStore \t at new_test.main(new_test.java:29)_ – sanjan

+0

'(String objectsToStore:objectsToStore)'此行错误 – sanjan

+0

您在循环中重复变量名称。应该是'(String objectToStore:objectsToStore) – maiorovi

0

如果你想拯救它们。 ..thn在循环外部声明一个字符串[] arrsy ....然后尝试使用嵌套循环在字符串内存储邮件地址...

而且您还可以使用FileIlnputStrem将它们存储在文本文件中类.... ina txt文件...

+0

我告诉这个答案将它们存储在一个变量和txt文件中...不是针对DB –

+0

但是OP在线程“main”中声明'DB' –