#include <iostream>
#include <mysql/mysql.h>

int main() {
    MYSQL *conn;
    conn = mysql_init(NULL);

    if (conn == NULL) {
        std::cerr << "MySQL init failed" << std::endl;
        return 1;
    }

    const char *server = "localhost";
    const char *user = "rtsw";
    const char *password = "123456";
    const char *database = "nginxdb";
    unsigned int port = 3306;

    if (mysql_real_connect(conn, server, user, password, database, port, NULL, 0) == NULL) {
        std::cerr << "Connection error: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }

    std::cout << "Successfully connected to the database" << std::endl;

    // 插入数据
    const char *insert_query = "INSERT INTO users (username, email) VALUES ('newuser', 'newuser@example.com')";
    if (mysql_query(conn, insert_query)) {
        std::cerr << "Insert error: " << mysql_error(conn) << std::endl;
    } else {
        std::cout << "Insert successful" << std::endl;
    }

    // 查询数据
    const char *select_query = "SELECT * FROM users";
    MYSQL_RES *result = mysql_store_result(conn);
    if (result) {
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(result))) {
            std::cout << "id: " << row[0] << ", username: " << row[1] << ", email: " << row[2] << std::endl;
        }
        mysql_free_result(result);
    } else {
        std::cerr << "Select error: " << mysql_error(conn) << std::endl;
    }

    // 更新数据
    const char *update_query = "UPDATE users SET email = 'newuser_updated@example.com' WHERE username = 'newuser'";
    if (mysql_query(conn, update_query)) {
        std::cerr << "Update error: " << mysql_error(conn) << std::endl;
    } else {
        std::cout << "Update successful" << std::endl;
    }

    // 删除数据
    const char *delete_query = "DELETE FROM users WHERE username = 'newuser'";
    if (mysql_query(conn, delete_query)) {
        std::cerr << "Delete error: " << mysql_error(conn) << std::endl;
    } else {
        std::cout << "Delete successful" << std::endl;
    }

    mysql_close(conn);
    return 0;
}