aws lambda使用java做数据库增删改查

原创
2023/07/21 12:49
阅读数 128
import java.sql.*;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class UserCRUDLambda implements RequestHandler<Request, Response> {

    private static final String JDBC_URL = "jdbc:mysql://your-database-endpoint:3306/your-database-name";
    private static final String USERNAME = "your-database-username";
    private static final String PASSWORD = "your-database-password";

    public Response handleRequest(Request request, Context context) {
        try {
            if ("GET".equals(request.getHttpMethod())) {
                return getAllUsers();
            } else if ("POST".equals(request.getHttpMethod())) {
                return addUser(request);
            } else if ("PUT".equals(request.getHttpMethod())) {
                return updateUser(request);
            } else if ("DELETE".equals(request.getHttpMethod())) {
                return deleteUser(request);
            } else {
                return new Response("Invalid HTTP Method");
            }
        } catch (Exception e) {
            return new Response("Error: " + e.getMessage());
        }
    }

    private Response getAllUsers() throws SQLException {
        try (Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("SELECT * FROM users")) {

            // Process the ResultSet and return the list of users
            // (Assuming there is a User class to represent user information)
            List<User> users = new ArrayList<>();
            while (resultSet.next()) {
                User user = new User(resultSet.getInt("id"),
                                     resultSet.getString("name"),
                                     resultSet.getString("email"));
                users.add(user);
            }

            return new Response(users);
        }
    }

    private Response addUser(Request request) throws SQLException {
        try (Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
             PreparedStatement statement = connection.prepareStatement(
                     "INSERT INTO users (name, email) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) {

            statement.setString(1, request.getName());
            statement.setString(2, request.getEmail());
            int affectedRows = statement.executeUpdate();

            if (affectedRows == 0) {
                throw new SQLException("Failed to add user.");
            }

            try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    int userId = generatedKeys.getInt(1);
                    return new Response("User added successfully. UserID: " + userId);
                } else {
                    throw new SQLException("Failed to add user, no ID obtained.");
                }
            }
        }
    }

    private Response updateUser(Request request) throws SQLException {
        try (Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
             PreparedStatement statement = connection.prepareStatement(
                     "UPDATE users SET name = ?, email = ? WHERE id = ?")) {

            statement.setString(1, request.getName());
            statement.setString(2, request.getEmail());
            statement.setInt(3, request.getId());
            int affectedRows = statement.executeUpdate();

            if (affectedRows == 0) {
                return new Response("User not found.");
            } else {
                return new Response("User updated successfully.");
            }
        }
    }

    private Response deleteUser(Request request) throws SQLException {
        try (Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
             PreparedStatement statement = connection.prepareStatement(
                     "DELETE FROM users WHERE id = ?")) {

            statement.setInt(1, request.getId());
            int affectedRows = statement.executeUpdate();

            if (affectedRows == 0) {
                return new Response("User not found.");
            } else {
                return new Response("User deleted successfully.");
            }
        }
    }
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部