在mysql数据库中导入csv文件

时间:2013-03-21 09:32:17

标签: mysql csv

我有一个包含8列的csv文件。当我将csv文件导入mysql数据库时,它忽略了第二列并将其余数据从其他列向左移动,请帮忙。

我认为问题在于csv文件,因为一些csv文件已成功上传。我该如何解决?

这是我将csv文件存储到数据库中的查询:

LOAD DATA INFILE '$file_name' INTO TABLE import
FIELDS TERMINATED BY '|'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(@srno,@customer_name,@date,@mobno,@city,@state,@type,@telecaller)
SET customer_name=@customer_name,date=@date,mobno=@mobno,city=@city,
state=@state,type=@type,telecaller=@telecaller,datetime='$datetime'

1 个答案:

答案 0 :(得分:-1)

这段代码对我有用。使用本地数据库进行测试。

package Example_Import;

import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.*;
import java.lang.String;
import java.util.Scanner;

public class Example {

    //import mysql-connector-java-5.1.32.jar
    //http://www.tutorialspoint.com/jdbc/jdbc-create-tables.htm
    private static String JDBC_URL = "jdbc:mysql://localhost:3306/sakila";
    private static String USER = "root";
    private static String PASSWORD = "2004";

    public static void main(String[] args) throws IOException {

        Connection myConnection = null;
        Statement statement = null;
        PreparedStatement preparedStatement = null;

        try{
            //CONNECTING TO THE DATABASE
            myConnection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);


            System.out.println("Connected to database"); //CONNECTED

            //CREATING TABLE IN THE DATABASE    
            System.out.println("Creating table in given database...");
            statement = myConnection.createStatement();

            String sql = "CREATE TABLE REGISTRATION " +
                           "(id INTEGER not NULL, " +
                           " last VARCHAR(25), " + 
                           " first VARCHAR(25), " + 
                           " balance FLOAT, " + 
                           " Credit FLOAT," +
                           " Date DATE," +
                           " Rating CHAR," +
                           " PRIMARY KEY ( id ))"; 

             statement.executeUpdate(sql);
             System.out.println("Created table in given database...");
             statement.close(); //closing statement


            //CREATING A PREPARED STATEMENT
            String insertTableSQL = "INSERT INTO REGISTRATION"
                    + "(id, last, first, balance, Credit, Date, Rating) VALUES"
                    + "(?,?,?,?, ?, ?, ?)";


            preparedStatement = myConnection.prepareStatement(insertTableSQL);

            //RETRIEVING INFORMATION FROM CSV FILE

            //opening a file input stream
            BufferedReader reader = new BufferedReader(new FileReader("SAMPLE.csv"));

            String line = null; //line read from csv
            Scanner scanner = null; //scanned line

            SimpleDateFormat date = new SimpleDateFormat("mm/DD/yyyy");

            reader.readLine(); //omits the first line

            //READING FILE LINE BY LINE AND UPLOADING INFORMATION TO DATABASE
            while((line = reader.readLine()) != null){
                scanner = new Scanner(line);
                scanner.useDelimiter(",");
                while(scanner.hasNext()){
                        preparedStatement.setInt(1,Integer.parseInt(scanner.next()));
                        preparedStatement.setString(2, scanner.next());
                        preparedStatement.setString(3, scanner.next());
                        preparedStatement.setFloat(4, Float.parseFloat(scanner.next()));
                        preparedStatement.setFloat(5, Float.parseFloat(scanner.next()));
                        try {
                            java.util.Date d;
                            d = date.parse(scanner.next());
                            preparedStatement.setDate(6, new java.sql.Date(d.getTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }   
                        preparedStatement.setString(7, scanner.next());
                    }   
                    preparedStatement.executeUpdate();
            }

            preparedStatement.close();
            System.out.println("Data imported");

            reader.close(); //closing CSV reader

        } catch (SQLException e){
            e.printStackTrace();
        }finally{//CLOSING CONNECTION
            try{
                 if(statement!=null)
                    myConnection.close();
              }catch(SQLException se){
              }// do nothing
              try{
                 if(myConnection!=null)
                    myConnection.close();
              }catch(SQLException se){
                 se.printStackTrace();
              }
              System.out.println("Connection closed");
        }
    }
}