JDBC for sqlite

JDBCはデータベースの接続(SQLite)

Jarのバージョンは、ここへ: sqlite-jdbc-3.7.15-m1.jar

SQLiteJDBC接続

  • データベースの接続SQLiteJDBCの搭載について
    sqlitejdbc-v033-nested.jar を配置する手順:
  • [lib]フォルダーを作成する
    右クリック[New]→[Folder]
  • フォルダの名前:「lib」入力
  • sqlitejdbc-v033-nested.jarをフォルダー[lib]にコピー
  • 右クリック[buld_path]
  • User Libraryとして追加すること
  • UserLibrary名前を入力
  • Jarファイルを追加すること

データベースの接続を取得する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private Connection getConnection() throws ClassNotFoundException {
        Connection connection = null;
        try {
            // SQLiteJDBCの駆動をロードする
            Class.forName("org.sqlite.JDBC");
            // 接続を確立する
            connection = DriverManager.getConnection("jdbc:sqlite://d:/Web/test.db");
            System.out.println("Connection success");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

test.db

データベースのクエリ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
private void testQuery() throws ClassNotFoundException {
        try {
            Connection connection = getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from users");
            while (resultSet.next()) {
                System.out.println("username = : " + resultSet.getString("username"));
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

データベースのインサート

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public void testInsert() throws ClassNotFoundException {
        try {
            Connection connection = getConnection();
            String insertSQL = "insert into users (userid,username) values (?,?)";

            PreparedStatement statement = connection.prepareStatement(insertSQL);
            statement.setInt(1, 3);
            statement.setString(2, "test3");

            int result = statement.executeUpdate();

            if (result != 0) {
                System.out.println("insert success");
            }

            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

データベースの削除する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
private void testDelete() throws ClassNotFoundException {
        try {
            Connection connection = getConnection();
            String insertSQL = "delete from users where userid = ?";

            PreparedStatement statement = connection.prepareStatement(insertSQL);
            statement.setInt(1, 3);

            int result = statement.executeUpdate();

            if (result != 0) {
                System.out.println("delete success");
            }

            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }