如何将csv中的值插入到java中的数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30726978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:04:21  来源:igfitidea点击:

How to insert values from csv into database in java

javacsv

提问by kittu

I have tried the following code to split the csv values and now how do insert it in to DB? Do I have save the values in to separate variables to match column names? I am unable to figure out.

我尝试了以下代码来拆分 csv 值,现在如何将其插入到数据库中?我是否将值保存到单独的变量中以匹配列名?我无法弄清楚。

Note: I don't want to use any csv parser right now. I just want to do it manually

注意:我现在不想使用任何 csv 解析器。我只想手动完成

public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        String name;
        String email;
        String phone;
        String ID;

        Connection con = OracleDBConnection.getConnection();
        String query = "Insert into NEWSTUDENT values(?,?,?,?)";
                PreparedStatement st = con.prepareStatement();
                st.executeUpdate(query);        

        try {
            BufferedReader bReader = new BufferedReader(new FileReader("1000rows.csv"));

            while (bReader != null) {
                String read;
                try {
                    read = bReader.readLine();
                    if (read != null) 
                    {
                        String[] array = read.split(",+");
                        for(String result:array)
                        {
                            System.out.println(result);
                        }
                    } 
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                finally
                {
                   if (bReader == null) 
                    {
                        bReader.close();
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }
}

output:

输出:

1Kiriti
[email protected]
880789939

Column names in Database:

数据库中的列名:

Name Email Phone ID

采纳答案by Rookie007

Use Parepared statement and build a query in while Loop and execute it. For more on Prepared Statement please check Check this link

使用 Parpared 语句并在 while 循环中构建查询并执行它。有关准备好的声明的更多信息,请检查检查此链接

String sql = " INSERT INTO TABLE_(name,email,phone,id) VALUES(?,?,?,?) ";


try { 
        BufferedReader bReader = new BufferedReader(new FileReader("1000rows.csv"));
        String line = ""; 
        while ((line = bReader.readLine()) != null) {
            try {

                if (line != null) 
                {
                    String[] array = line.split(",+");
                    for(String result:array)
                    {
                        System.out.println(result);
 //Create preparedStatement here and set them and excute them
                PreparedStatement ps = yourConnecionObject.createPreparedStatement(sql);
                 ps.setString(1,str[0]);
                 ps.setString(2,str[1]);
                 ps.setString(3,str[2]);
                 ps.setString(4,strp[3])
                 ps.excuteUpdate();
                 ps. close()
   //Assuming that your line from file after split will folllow that sequence

                    }
                } 
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            finally
            {
               if (bReader == null) 
                {
                    bReader.close();
                }
            }
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }

回答by Jens

You can store your data in an array and bind them to your statement:

您可以将数据存储在数组中并将它们绑定到您的语句:

 String query = "Insert into NEWSTUDENT values(?,?,?,?)";

 PreparedStatement st = con.prepareStatement(query);
 st.setString(1,array [0]);
 st.setString(2,array[1]);
 ....
 st.executeUpdate();        

For more informations about prepared statements see the oracle documentation

有关准备好的语句的更多信息,请参阅oracle 文档

回答by Neeraj Jain

You can use Prepare Statementand set the value in parameter at each iteration:

您可以Prepare Statement在每次迭代时使用和设置参数中的值:

Connection con = OracleDBConnection.getConnection();
String query = "Insert into NEWSTUDENT values(?,?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1,array[0]);
ps.setString(2,array[1]); // and so on
ps.executeUpdate();

If No of Rows are more you can also use Batch Processing :

如果行数更多,您还可以使用批处理:

String sql = "Insert into NEWSTUDENT values(?,?,?)";


PreparedStatement preparedStatement = null;
try{
    preparedStatement =
            connection.prepareStatement(sql);

    preparedStatement.setString(1, "Gary");
    preparedStatement.setString(2, "Larson");
    preparedStatement.setString (3, "Test");

    preparedStatement.addBatch();

    preparedStatement.setString(1, "Stan");
    preparedStatement.setString(2, "Lee");
    preparedStatement.setString (3, 456);

    preparedStatement.addBatch();

    int[] affectedRecords = preparedStatement.executeBatch();

}finally {
    if(preparedStatement != null) {
        preparedStatement.close();
    }
}