AtsushiUtsumi / dbtest

spring CLI と sqlite
0 stars 0 forks source link

どうやって作ったかといううと #1

Open AtsushiUtsumi opened 1 year ago

AtsushiUtsumi commented 1 year ago

まずはSpring CLIで新規Springプロジェクト作成

spring init -d=web --build=maven -n=dbtest dbtest
AtsushiUtsumi commented 1 year ago

SQLiteの依存関係追加のために「pom.xml」に追加

        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
        </dependency>
AtsushiUtsumi commented 1 year ago

コントローラ追加

package com.example.dbtest.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.dbtest.TestRepository;

/**
 * TestController
 */
@Controller
@RequestMapping("/")
@ResponseBody
public class TestController {
    @GetMapping()
    public String index(){
        return "ホーム画面だよ";
    }

    @GetMapping("db")
    public String db() {
        var x = new TestRepository();
        return "DB" + x.hoge();
    }
}
AtsushiUtsumi commented 1 year ago

Sqliteを使ったファイルを追加

package com.example.dbtest;

import java.sql.*;

public class TestRepository {
    public String hoge() {

        Connection connection = null;
        Statement statement = null;

        try {
            Class.forName("org.sqlite.JDBC");

            // データベースのPATHを指定。相対パスでも絶対パスでも行けるようです
            connection = DriverManager.getConnection("jdbc:sqlite:test.db");
            statement = connection.createStatement();
            String sql = "select * from table1 where id=5";
            //String sql = "CREATE TABLE table1(id INTEGER PRIMARY KEY, name TEXT NOT NULL)";
            //String sql = "INSERT INTO table1(id, name) VALUES(2,22)";
            //String sql = "INSERT INTO table1(id, name) VALUES(5,'utsumi')";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                return rs.getString(1) + ":" + rs.getString(2);
            }
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        } catch (SQLException e) {
          e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}