Help!! parse text file and update database thru jdbc
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   ken_lo
Posted On:   Monday, January 14, 2002 09:25 PM

import java.io.*; import java.sql.*; import java.util.*; public class TxtToData { private static final String DB = "contacts", TABLE_NAME = "BOM1", FILENAME = "bom.txt"; public static void main (String[] args) { try { // connect to db Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:Odbc:db1", "" , ""); Statement stmt = con.createStatement(); // open text file BufferedReader in = new BufferedReader( new FileReader(FILENAME));    More>>

import java.io.*;

import java.sql.*;

import java.util.*;


public class TxtToData {

private static final String DB = "contacts",

TABLE_NAME = "BOM1",

FILENAME = "bom.txt";


public static void main (String[] args) {

try {


// connect to db


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:Odbc:db1", "" , "");

Statement stmt = con.createStatement();


// open text file

BufferedReader in = new BufferedReader(

new FileReader(FILENAME));


// read and parse a line

String line = in.readLine();

while(line != null) {

String delim = "|";

StringTokenizer tk = new StringTokenizer(line);

String Quantity = tk.nextToken(delim),

Part_number = tk.nextToken(delim),

Type = tk.nextToken(delim),

Product_description = tk.nextToken(delim);


// execute SQL insert statement

String query = "INSERT INTO " + TABLE_NAME;

query += " VALUES(" + quote(Quantity) + ", ";

query += quote(Part_number) + ", ";

query += quote(Type) + ", ";

query += quote(Product_description) + ");";

stmt.executeQuery(query);


// prepare to process next line

line = in.readLine();

}

in.close();

}


catch( Exception e) {

e.printStackTrace();

}

}


// protect data with quotes

private static String quote(String include) {

return(""" + include + """);

}

}


the sample bom.txt file look like this

1|pin|part|this is a pin


Am i doing the right thing? pls help
Your help will be greatly appreciated

   <<Less

Re: Help!! parse text file and update database thru jdbc

Posted By:   Anonymous  
Posted On:   Tuesday, January 15, 2002 02:44 AM

There are many possible solutions to similar problems. Some people will prefer using xml, some other will still prefer solution like yours.


My only note is on the insert statement. Instead of creating the statement, you should use the PreparedStatement interface that will simplify your work.

You could use updatable ResultSet, but I'm afraid that the standard jdbc-odbc bridge doesn't support it.


Regards

About | Sitemap | Contact