· 7 years ago · Nov 02, 2018, 06:10 AM
1package com.example;
2
3import java.io.FileReader;
4import java.io.IOException;
5import java.sql.Connection;
6import java.sql.DriverManager;
7import java.sql.PreparedStatement;
8import java.sql.Statement;
9import java.sql.SQLException;
10
11import com.opencsv.CSVReader;
12
13
14public class Demo {
15 private final static String CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS persons ("
16 + "id INTEGER PRIMARY KEY, "
17 + "name TEXT NOT NULL, "
18 + "age INTEGER NOT NULL)";
19 private final static String INSERT_PERSON_QUERY = "INSERT INTO persons (name, age) VALUES (?, ?)";
20
21
22 public static void main(String[] args) {
23 try (Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db")) {
24 try (Statement stmt = connection.createStatement()) {
25 stmt.execute(CREATE_TABLE_QUERY);
26 }
27 catch (SQLException exc) {
28 exc.printStackTrace();
29 }
30
31 try (CSVReader reader = new CSVReader(new FileReader("test.csv"));
32 PreparedStatement stmt = connection.prepareStatement(INSERT_PERSON_QUERY)) {
33 String[] record;
34 while ((record = reader.readNext()) != null) {
35 stmt.setString(1, record[0]);
36 stmt.setInt(2, Integer.valueOf(record[1]));
37 stmt.executeUpdate();
38 }
39 }
40 catch(IOException exc) {
41 exc.printStackTrace();
42 }
43 catch (SQLException exc) {
44 exc.printStackTrace();
45 }
46 }
47 catch (SQLException exc) {
48 exc.printStackTrace();
49 }
50 }
51}
52
53John,30
54Jack,28
55Jimm,41