ZBLOG

c++ mysql 判断表是否存在

使用以下代码来判断MySQL数据库中是否存在指定的表:

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

using namespace std;

int main() {
    MYSQL* conn;
    MYSQL_RES* res;
    MYSQL_ROW row;
    const char* host = "localhost";
    const char* user = "root";
    const char* passwd = "password";
    const char* db = "testdb"; // database name
    const char* table = "mytable"; // table name

    conn = mysql_init(NULL);

    if (!mysql_real_connect(conn, host, user, passwd, db, 0, NULL, 0)) {
        cout << "Error: " << mysql_error(conn) << endl;
        return 1;
    }

    string query = "SELECT * FROM " + string(table) + " LIMIT 1;";
    if (mysql_query(conn, query.c_str())) { // execute the query
        cout << "Error: " << mysql_error(conn) << endl;
        return 1;
    }

    res = mysql_store_result(conn);
    if (res) { // if result set is not empty, table exists
        cout << "Table " << table << " exists." << endl;
    } else { // otherwise, table does not exist
        cout << "Table " << table << " does not exist." << endl;
    }

    mysql_free_result(res);
    mysql_close(conn);

    return 0;
}

该程序创建一个连接到MySQL数据库的对象,并使用mysql_real_connect()函数连接到数据库。然后,它构建一个SELECT查询,将其发送到服务器,并使用mysql_store_result()函数获取结果集。如果结果集不为空,则表存在。否则,表不存在。

注意:该程序假设你已经安装了MySQL C++ Connector,且编译时需要链接到mysqlclient库。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1024

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?