Java code to Import text file to mysql
1) choose text file from computer
2) read that line by line
3) connect to mysql database
4) create table as an text file name
5) first line in text file is fields in mysql table. (problem here)
6) import data from second line to last line in that table
here is my code.
package com.mkyong.io;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class choosetextfile11 {
public static void main(String[] args)throws Exception {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter ("Text/Java files", "txt", "java");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
BufferedReader br = new BufferedReader (new FileReader(f));
String st = "";
while((st = br.readLine()) != null) {
System.out.println(st);
}
String Driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/jayraj1";
String uName ="root";
String pwd = "basiqa";
Connection conn=null;
Class.forName(Driver).newInstance();
conn = DriverManager.getConnection(url, uName, pwd);
Statement stmt = conn.createStatement();
//Problem here
[B] String sql = "create table " + f.getName().toString() + "( FIELDS name first line in text file varchar(60),department varchar(5),subject_name varchar(25))";
System.out.println(sql);
stmt.executeUpdate(sql);
System.out.println("CreateTable sucessfully");
}
}
}
please help me!!