简体   繁体   English

在MySQL数据库中导入CSV文件

[英]Importing csv file in mysql database

I have a csv file with 8 columns. 我有一个8列的csv文件。 When I am importing the csv file into mysql database, it is ignoring the 2nd column and shifting the rest of the data from the other columns to the left, please help. 当我将csv文件导入mysql数据库时,它会忽略第二列,并将其余数据从其他列移到左侧,请提供帮助。

I think the problem is with the csv file as some csv files are uploaded successfully. 我认为问题在于csv文件,因为某些csv文件已成功上传。 How can I fix it? 我该如何解决?

This is my query to store csv file into database: 这是我将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'

This code worked for me. 这段代码对我有用。 Test it out with a local database. 用本地数据库进行测试。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM