2017-07-20 35 views
2

當創建隨機電子郵件和存儲在MySQL數據庫其工作正常,然後我嘗試打印該隨機電子郵件,但我不能。任何人都可以幫助我在哪裏編輯我的代碼? 沒有ResultSet rs=statement.executeQuery("select * from user_data");System.out.println(rs.getString(1));其做工精細
注: - 有人請編輯我的語法java循環存儲數據庫並回調錯誤

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); 
     } 

    } 

} 
+0

給我們的錯誤stacktrace和數據庫模式 – Emax

+0

Random rad = new Random();在這一行語法錯誤 – sanjan

+0

我可以編譯你的代碼而沒有任何語法錯誤 – Emax

回答

1

問題是我剛搬到了線

的順序,你是使用的數據庫 執行查詢
ResultSet rs = statement.executeQuery("select * from user_data"); 

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

這不能解決問題,因爲當您從SELECT 執行UPDATE(第二查詢)ResultSet中獲得通過的聲明關閉,所以你不能重複它,並給你一個錯誤

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); 
} 
+0

哎呀非常感謝你的工作:D – sanjan