How to import a tab delimited file in MySQL database using Java?
I want to import a tab delimited file in MySQL database. How I can do this using开发者_Go百科 Java?
This is very vague, but it sounds like a mysql specific question. Here's the manual for loading files. The default is:
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED BY '\n' STARTING BY ''
Import a tab delimited file into MySQL:
Create your table:
mysql> create table foo(id INT, mytext TEXT, sparkle DECIMAL(9,4)); Query OK, 0 rows affected (0.02 sec)
Create your data file, put this in foo.txt, note tabs delimit the 3 columns
1 twilight sparkle is best pony! 6.6 2 pinkie pie is best pony! 3.3 3 derpy hooves is best pony! 1.1
Then import the file:
mysqlimport --fields-terminated-by='\t' --columns=id,mytext,sparkle --local -u root -ppassword your_database foo.txt yourdatabase.foo: Records: 4 Deleted: 0 Skipped: 0 Warnings: 3
Look in the table.
mysql> select * from foo; +------+-------------------------------+---------+ | id | mytext | sparkle | +------+-------------------------------+---------+ | 1 | twilight sparkle is best pony | 6.6000 | | 2 | pinkie pie is best pony | 3.3000 | | 3 | derpy hooves is best pony | 1.1000 | +------+-------------------------------+---------+ 4 rows in set (0.00 sec)
The rows were loaded.
Read up on my mysqlimport command to see all the things it can do.
http://dev.mysql.com/doc/refman/5.0/en/mysqlimport.html
Use Scanner API to read file and create your dynamic SQL statements. After that use JDBC preparedStatement and execute them.
Open a JDBC connection to your database. Create a prepared statement to insert a row in your table. Read the file line by line. You might use something like OpenCSV to help you. For each line, bind the parameters of the prepared statement and execute it. Close the prepared statement, the connection and the file reader.
Read http://download.oracle.com/javase/tutorial/jdbc/basics/index.html to learn JDBC.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("myfile.tab")));
String line = null;
while((line = reader.readLine()) != null) {
String[] fiedls = line.split("\\t");
// generate your SQL insert statement here
// execute SQL insert.
}
If you are not familier with SQL and/or JDBC refer to appropriate tutorial. Google will help you to find one.
精彩评论