2017-07-20 103 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' –