ZBLOG

c++ mysql 判断表是否存在

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

  1. #include <iostream>
  2. #include <mysql.h>
  3. using namespace std;
  4. int main() {
  5. MYSQL* conn;
  6. MYSQL_RES* res;
  7. MYSQL_ROW row;
  8. const char* host = "localhost";
  9. const char* user = "root";
  10. const char* passwd = "password";
  11. const char* db = "testdb"; // database name
  12. const char* table = "mytable"; // table name
  13. conn = mysql_init(NULL);
  14. if (!mysql_real_connect(conn, host, user, passwd, db, 0, NULL, 0)) {
  15. cout << "Error: " << mysql_error(conn) << endl;
  16. return 1;
  17. }
  18. string query = "SELECT * FROM " + string(table) + " LIMIT 1;";
  19. if (mysql_query(conn, query.c_str())) { // execute the query
  20. cout << "Error: " << mysql_error(conn) << endl;
  21. return 1;
  22. }
  23. res = mysql_store_result(conn);
  24. if (res) { // if result set is not empty, table exists
  25. cout << "Table " << table << " exists." << endl;
  26. } else { // otherwise, table does not exist
  27. cout << "Table " << table << " does not exist." << endl;
  28. }
  29. mysql_free_result(res);
  30. mysql_close(conn);
  31. return 0;
  32. }

该程序创建一个连接到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

注册

已经有帐号?