Write a Java Program that takes tab separated data (one record per line) from a text file and inserts them into a database.

Program Code:
import java.sql.*;
import java.io.*;
import java.util.*;
public class Tbltodb {
public static void main(String[] args) 
{
Connection cn;
Statement st;
try
{
cn=DriverManager.getConnection("jdbc:mysql://localhost/jdbc","root","Gcet@05");
st=cn.createStatement();
String sql="";
FileInputStream fin=new FileInputStream("D:\\abc.txt");
Scanner sc=new Scanner(fin);
String[] arrayList;
String a="";
int i=0;
while(sc.hasNext())
{
a=sc.nextLine();
arrayList =a.split("\\s+");
sql="insert into emp values("+"'"+arrayList[0]+"','"+arrayList[1]+"')";
st.execute(sql);
i++;
System.out.println(arrayList[0]+":"+arrayList[1]);
}
System.out.println(i+" Records are inserted");
st.close();
cn.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

abc.txt
Mukesh 123
Ravi 456
Raja 678

MYSQL
MYSQL>create database jdbc;
MYSQL> use jdbc;
MYSQL>create table emp(name varchar(20),phonenum int);

Output:
Mukesh:123
Ravi:456
Raja:678
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: