Read a complete file and Insert it into database using Java

Hello Friends,

The example below demonstrates How you can read the whole file contents and write at once in database.

This program will read all the contents in form of bytes and will insert it into database table before passing it to the insert method it has been converted into string.

This program is useful when you want to read a file and insert its contents into database table.

1. DBConn.java

package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Sudhanshu
 */
public class DBConn {
    private static Connection con;
    private final static String userName=”root”;
    private final static String password=”mysql”;
    private final static String host=”localhost”;
    private final static String port=”3306″;
    private final static String dbName=”oxyzium”;
    private final static String driver=”com.mysql.jdbc.Driver”;
    private final static String url=”jdbc:mysql://”+host+”:”+port+”/”+dbName;
   
    static{
        try {
           
            //System.out.println(“Driver Loading….”);
            Class.forName(driver);
            //System.out.println(“Driver Loaded”);
        } catch (ClassNotFoundException ex) {
           System.out.println(ex);
        }
      
    }
   
   
   
    public static Connection getConnection() throws SQLException{
   
            if((con==null)||(con.isClosed())){
               // System.out.println(“Creating Connection….”);
                con=DriverManager.getConnection(url, userName, password);
                //System.out.println(“Connection…. created”);
            }
        return con;
    }
   
}
2. CreateTable.java

package db;

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

/**
 *
 * @author Sudhanshu
 */
public class CreateTable {

    private String query=”CREATE TABLE IF NOT EXISTS `datainfo` (“
            + “sno integer(10) not null primary key, “
            + “data longtext NOT NULL”
            + “)”;
   
    public boolean createTable(Statement stmt){
        try{
             stmt.executeUpdate(query);
             return true;
        }catch(SQLException e){
             System.out.println(“Error in creating table : “+e);
             return false;
        }
    }
}
3. Insert.java

package db;

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

/**
 *
 * @author Sudhanshu
 */
public class Insert {
    private Connection con;
    private Statement stmt;
    public Insert(){
       
    }
    public boolean insert(int sno, String data){
        try{
            this.con=DBConn.getConnection();
            this.stmt=con.createStatement();
           
            CreateTable ct=new CreateTable();
            boolean b=ct.createTable(this.stmt);
           
            if(b){
                stmt.executeUpdate(“INSERT INTO `datainfo` VALUES( ‘”+sno+”‘, ‘”+data+”‘)”);
                stmt.close();
                con.close();
                return true;
            }else{
                return false;
            }
           
         }catch(SQLException ex){
            System.out.println(“GET: “+ex);
            return false;
        }
    }
}
4. Query.java

package db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Sudhanshu
 */
public class Query {
   
    private Connection con;
    private PreparedStatement pstm;
    public void show(){
       try{
            this.con=DBConn.getConnection();
            this.pstm=con.prepareStatement(“SELECT * FROM datainfo”);
            ResultSet rset=pstm.executeQuery();
            while(rset.next()){
                System.out.println(rset.getString(“data”));
            }
       }catch(Exception e){
            System.out.println(“EXX:”+e);
        }
      }
}
5. ReadWriteDatabase.java

package readwritedatabase;

import db.Insert;
import java.io.FileInputStream;
import java.io.IOException;

/**
 *
 * @author Sudhanshu
 */
public class ReadWriteDatabase {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
         FileInputStream fis = new FileInputStream(“E://core//io//NB//myfile.txt”);
            byte[] b=new byte[fis.available()];
            fis.read(b);
            String s=new String(b);
            Insert i=new Insert();
            i.insert(2, s);
   
    }
}
6. Read.java

package readwritedatabase;

import db.Query;

/**
 *
 * @author Sudhanshu
 */
public class Read {
     public static void main(String[] args){
         Query q=new Query();
         q.show();
     }
}

Note.:
1. Install mysql server and put the reference of mysql connector in classpath
2. Compile all the files and execute the main class.
Please use appropriate file address and make changes according to the file location in program ReadWriteDatabase.java before compiling.