c++ mysql库的数据更新与删除操作

c++
911
2024/8/26 15:32:11
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用MySQL C++ Connector库来进行数据更新和删除操作。以下是一个简单的示例代码,展示如何使用MySQL C++ Connector库来进行数据更新和删除操作:

数据更新操作示例:

#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

int main() {
    sql::mysql::MySQL_Driver *driver;
    sql::Connection *con;

    driver = sql::mysql::get_mysql_driver_instance();
    con = driver->connect("tcp://127.0.0.1:3306", "username", "password");
    con->setSchema("database_name");

    sql::PreparedStatement *pstmt;
    std::string query = "UPDATE table_name SET column1 = ? WHERE column2 = ?";
    pstmt = con->prepareStatement(query);
    pstmt->setString(1, "new_value");
    pstmt->setString(2, "value_to_match");
    pstmt->executeUpdate();

    delete pstmt;
    delete con;

    return 0;
}

数据删除操作示例:

#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>

int main() {
    sql::mysql::MySQL_Driver *driver;
    sql::Connection *con;

    driver = sql::mysql::get_mysql_driver_instance();
    con = driver->connect("tcp://127.0.0.1:3306", "username", "password");
    con->setSchema("database_name");

    sql::Statement *stmt;
    stmt = con->createStatement();
    std::string query = "DELETE FROM table_name WHERE column = 'value'";
    stmt->execute(query);

    delete stmt;
    delete con;

    return 0;
}

在以上示例代码中,需要将usernamepassworddatabase_nametable_namecolumn1column2value_to_match替换为实际的数据库连接信息和表、列名等。同时,需要确保已经安装了MySQL C++ Connector库,并在编译时链接该库。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++中getcurrenttime函数怎么使用