Import Data from Txt or CSV files into MYSQL database tables

 

Mysql-connector-java-3.1.10 is a JDBC connector for MYSQL database. MYSQL provides LOAD DATA INFILE utility to import data from files like csv, txt or xls into database tables.

The example below imports data from .txt file into table.

temp.txt file is a tab separated file:

"1 string"      100
"2 string" 102
"3 string" 104
"4 string" 106
testtable structure
CREATE TABLE testtable
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
text varchar(45) NOT NULL,
price integer not null);
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public  class  automateImport
{
    public static void main(String[] args
    {
        DBase  db  = new DBase();
        Connection conn = db.connect(
    "jdbc:mysql://localhost:3306/test","root","caspian");
        db.importData(conn,args[0]);
    }

}

class DBase
{
    public DBase()
    {
    }

    public Connection connect(String db_connect_str, 
  String db_userid, String db_password)
    {
        Connection conn;
        try 
        {
            Class.forName(  
    "com.mysql.jdbc.Driver").newInstance();

            conn = DriverManager.getConnection(db_connect_str, 
    db_userid, db_password);
        
        }
        catch(Exception e)
        {
            e.printStackTrace();
            conn = null;
        }

        return conn;    
    }
    
    public void importData(Connection conn,String filename)
    {
        Statement stmt;
        String query;

        try
        {
            stmt = conn.createStatement(
    ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_UPDATABLE);

            query = "LOAD DATA INFILE '"+filename+
    "' INTO TABLE testtable (text,price);";

            stmt.executeUpdate(query);
                
        }
        catch(Exception e)
        {
            e.printStackTrace();
            stmt = null;
        }
    }
};

If you want to import a CSV file, you can use the following query:

query = "LOAD DATA INFILE '"+filename+"' INTO TABLE testtable  FIELDS
TERMINATED BY ',' (text,price)";
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值