Java Program to Import data from textfile to mysql Database


Mysql Posses the functionality  to import data from txt,csv files..Following program helps to import sample text data in to table in database.

Sample data need to be imported


temp.txt file 
--------------


"1 string"      100

"2 string"      102
"3 string"      104
"4 string"      106
  

Table Structure



CREATE TABLE testtable

(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

text varchar(45) NOT NULL,
price integer not null);

Java Program

 
// Comment

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


raja P Web Developer

4 comments:

  1. Your technical information related with java programming is very useful and interesting. Also share updated details about java in your website. Thanks for sharing this article.

    ReplyDelete
  2. This information you provided in the blog that was really unique I love it!!, Thanks for sharing such a great blog..Keep posting..

    JAVA J2EE Training in Chennai

    ReplyDelete
  3. Nice program in Android. I face some issues and errors with the above code. Can you plz check the code once again ?

    Best Java J2EE Training in Chennai
    Best Java J2EE Training in Chennai

    ReplyDelete
  4. Hi Admin, I went through your article and it’s totally awesome. You can consider including RSS feed for easy content sharing, So that you can drive huge traffic to your blog
    Regards,

    Regards,
    CCNA Training in Chennai | CCNA Training Institute in Chennai | Best CCNA Training in Chennai

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...