-1

我需要将 ArrayList 中的每个项目添加到数据库中。我可以让 for each 循环将文件中的每个行项输出到控制台窗口,但是我将如何使用此循环将每个项添加到 mysql 数据库行?

    FileInputStream fstream = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    StringBuffer sb = new StringBuffer();
    ArrayList<String> store = new ArrayList<String>();
    String strLine;

    //Read File Line By Line
while((strLine = br.readLine())!= null)
{
    String [] splitLine = strLine.split(" \n");
    for(String x : splitLine)
    {

        System.out.println("Line: "+ x +"\n");

    }
}

- - - 更新 - -

好的,我修改了代码

    FileInputStream fstream = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;

        while((strLine = br.readLine())!= null)
            {
                String [] splitLine = strLine.split(" \n");
                for(int i=0;i<splitLine.length;i++)
                {           
                    // Prepare the query and values to be inserted into the database 
                    String str="INSERT INTO donations(name,charity,amount) VALUES (?,?,?)";

                    java.sql.PreparedStatement statement = conn.prepareStatement(str); 
                        String db1 = splitLine[0];
                        String db2 = splitLine[1];
                        Double db3 = Double.parseDouble(splitLine[2]);

                    statement.setString(1,db1);
                    statement.setString(2,db2);
                    statement.setDouble(3,db3);


                System.out.println("Line: "+ splitLine[i]+ " -record- " + i);

                }
            }
4

1 回答 1

0

您可以使用休眠并为数据库表创建一个 POJO。您可以创建此 POJO 的数组列表,保存后,数组列表将(批量)插入数据库中。

于 2013-03-25T19:29:26.763 回答