Loading a Flat File to a MySQL Table - Java JDBC

Java examples for JDBC:MySQL

Description

Loading a Flat File to a MySQL Table

Demo Code

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
  public static void main(String[] argv) {
    try {//  ww  w. j av a 2  s .  co  m
      Connection connection = null;
      // Create the statement
      Statement stmt = connection.createStatement();

      // Load the data
      String filename = "c:\\\\temp\\\\infile.txt";
      String tablename = "mytable";
      stmt.executeUpdate("LOAD DATA INFILE \"" + filename + "\" INTO TABLE "
          + tablename);

      // If the file is comma-separated, use this statement
      stmt.executeUpdate("LOAD DATA INFILE \"" + filename + "\" INTO TABLE "
          + tablename + " FIELDS TERMINATED BY ','");

      // If the file is terminated by \r\n, use this statement
      stmt.executeUpdate("LOAD DATA INFILE \"" + filename + "\" INTO TABLE "
          + tablename + " LINES TERMINATED BY '\\r\\n'");
    } catch (SQLException e) {
    }
  }
}

Related Tutorials