完成数据库更新
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package TodoListApp.src;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DatabaseManager {
|
||||
private static final String URL = "jdbc:mysql://localhost:3306/TodoList";
|
||||
private static final String USER = "root";
|
||||
private static final String PASSWORD = "123456";
|
||||
|
||||
public DatabaseManager() {
|
||||
try {
|
||||
Class.forName("com.mysql.cj.jdbc.Driver");
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void addTodo(String description) throws SQLException {
|
||||
String sql = "INSERT INTO todos (description) VALUES (?)";
|
||||
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql)) {
|
||||
pstmt.setString(1, description);
|
||||
pstmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
public List<TodoItem> getAllTodos() throws SQLException {
|
||||
List<TodoItem> todos = new ArrayList<>();
|
||||
String sql = "SELECT * FROM todos";
|
||||
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(sql)) {
|
||||
while (rs.next()) {
|
||||
int id = rs.getInt("id");
|
||||
String description = rs.getString("description");
|
||||
todos.add(new TodoItem(id, description));
|
||||
}
|
||||
}
|
||||
return todos;
|
||||
}
|
||||
|
||||
public void removeTodo(int id) throws SQLException {
|
||||
String sql = "DELETE FROM todos WHERE id = ?";
|
||||
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql)) {
|
||||
pstmt.setInt(1, id);
|
||||
pstmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
public void markAsCompleted(int id) throws SQLException {
|
||||
String sql = "UPDATE todos SET completed = true WHERE id = ?";
|
||||
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql)) {
|
||||
pstmt.setInt(1, id);
|
||||
pstmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user