Inserting Values From Text File To MySQL
Kushal Paudyal August 23rd, 2010
package com.kushal.utilities;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertTextFromFileToMySql {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/sanjaal_com";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,
username, password);
return conn;
}
public static void main(String[] args) throws Exception {
String textValue = "";
int textLength = 0;
String category = "funny";
String lineRead = null;
PreparedStatement pstmt = null;
String fileNameToInsertTextFrom = "C:/temp/smsCollection002.txt";
FileReader fileReader = new FileReader(new File(
fileNameToInsertTextFrom));
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
BufferedReader reader = new BufferedReader(fileReader);
pstmt = conn.prepareStatement(
"insert into smsTable(sms_text, sms_length, sms_category)"+
"values (?, ?, ?)");
while ((lineRead = reader.readLine()) != null) {
try {
textValue = lineRead.trim();
textLength = textValue.length();
if (textLength > 0) {
pstmt.setString(1, textValue);
pstmt.setInt(2, textLength);
pstmt.setString(3, category);
pstmt.executeUpdate();
conn.commit();
}
} catch (NullPointerException npe) {
// do nothing proceed to another line
}
lineRead = null;
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
}
Sanjaal.com is owned and maintained by Sanjaal Corps, Nepal. The company offers Webhosting and Domain Registration Services, IT Solutions and Business Analysis. Sanjaal.com website features H1B Visa Information, Entertainment Portal, Link Directory Service, Free Articles, Free Open Source Tutorials on Java and J2EE Platform, Digital Photography, High Resolution Picture Gallery and Free Reliable Image Hosting Services. Future plan includes Open Source Software Development Portal, Technical Solutions and Customizable Movie and Music Arena. We would be introducing data backup, data recovery, data hosting and voip solutions. Stay free from phishing – our website does not ask for your credit card and banking information. Happy Surfing!
Originally posted 2008-07-04 14:33:22.