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
Post A Comment:
0 comments: