Reputation: 59
I'm starting learning Java and need some help. I need to import CSV file into SQLite database. I have this CSV reader, but i don't know how to copy this data into SQLite database.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class csv {
public static void main(String[] args) {
String csvFile = "/home/user/user.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] table = line.split(cvsSplitBy);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Upvotes: 2
Views: 6214
Reputation: 4239
You can use JDBC and prepared statements (check this documentation https://docs.oracle.com/javase/8/docs/api/index.html?java/sql/PreparedStatement.html )
Download some JDBC driver for SQLite. For example, here https://github.com/xerial/sqlite-jdbc
Add JDBC jar to your classpath.
Write something like that:
String dbName = "insert your db name here";
Connection conn = null;
try {
// use your dbname instead
conn = DriverManager.getConnection("jdbc:sqlite:dbname");
// use your tablename instead; set as much question marks as many fields you have
PreparedStatement stmt =
conn.prepareStatement("insert into tablename (column1, column2, column3) values (?, ?, ?)");
br = ...;
while (line = ...) {
String[] table = ...;
// set values to replace question marks in prepared statement
stmt.setInt(1, table[0]);
stmt.setString(2, table[1]);
stmt.setString(3, table[2]);
// so, know your statement is like insert into ... values (table[0], table[1], table[2])
// and maybe add other fields...
stmt.executeUpdate(); // insert data into table
}
} catch (...) { ...
} finally { ...close conn and br... }
Upvotes: 1
Reputation: 6435
if your loop stays like this you have to iterate through the array each line and pick the values and write them to your database. to write data to a sqlite database you should use google. you will find plenty examples on how to do that
Upvotes: 0