Open AtsushiUtsumi opened 1 year ago
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
</dependency>
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();
}
}
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 "";
}
}
まずはSpring CLIで新規Springプロジェクト作成