CSV进入MySQL数据库

时间:2015-04-02 09:32:16

标签: java mysql

我有以下代码段:

    String insertSql =  "LOAD DATA INFILE 'C:/thomsonReuters/compressed/premium-world-check-day.csv'"
                    + " INTO TABLE thomsenreuters.worldcheck " 
                    + " FIELDS TERMINATED BY '\t' " 
                    + " ENCLOSED BY '\"' " 
                    + " LINES TERMINATED BY '\r\n' " 
                    + " IGNORE 1 ROWS;";

此文件总共有4567行。这些字段由制表符终止,并用双引号括起来。我尝试通过Prepared-Update stmt插入csv文件。但Java只将前4行插入MySQL。我做过的错误是什么?

感谢您的帮助

修改

完整课程代码:

Connection con = null;
    PreparedStatement stmt = null;

    String truncateTable = "Truncate table thomsenreuters.worldcheck;";

    String insertSql =  "LOAD DATA INFILE 'C:/thomsonReuters/compressed/premium-world-check-day.csv'"
                    + " INTO TABLE thomsenreuters.worldcheck " 
                    + " FIELDS TERMINATED BY '\t' " 
                    + " ENCLOSED BY '\"' " 
                    + " LINES TERMINATED BY '\r\n' " 
                    + " IGNORE 1 ROWS;";    

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {            
        e.printStackTrace();
    }

    System.out.println("Driver was found");

    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/thomsenreuters","XXXXXXX","XXXXXXX");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    System.out.println("Connection to Database");

    System.out.println("Start insert...");
    try {
        con.setAutoCommit(false);
        stmt = con.prepareStatement(truncateTable);
        stmt = con.prepareStatement(insertSql);         
        int total  = stmt.executeUpdate();
        con.commit();
        con.setAutoCommit(true);

        System.out.println("Total Rows insert " + total);



    } catch (SQLException e) {
        e.printStackTrace();
    }
    finally{
        if(stmt != null)
        {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con != null)
        {
            try {
                con.close();
            } catch (SQLException e) {                  
                e.printStackTrace();
            }
        }
    }


}

0 个答案:

没有答案