c++ - 在 MySql 中使用字符串操作函数会出现什么问题?

标签 c++ mysql windows 64-bit

我有一个 MySQL 8.0.17 数据库示例项目,我正在 64 位 Windows 计算机上使用 Visual Studio CE 2017 进行编译。它是一个控制台应用程序。请参阅样板下面的代码。我遇到的问题是在初始化数据库后尝试操作字符串时。即:取消注释 sprintf_s() 会导致抛出异常。我想了解这是否是设计使然或者是一个错误?或者我可能做错了什么?

include "pch.h"
include <windows.h> 
include <iostream> 
include <winsock.h> 
include <stdio.h> 
include <mysql.h>

int main()
{   std::cout << "Hello World!\n";
    MYSQL conn;
    MYSQL_RES *res_set;
    MYSQL_ROW row;

    mysql_init(&conn);

    char str[6];
 // sprintf_s(str, 5, "test");

    if(!mysql_real_connect(&conn,"localhost","usr","pas","db",0,NULL,0))
    {   fprintf(stderr, "Connection Failed: %s\n", mysql_error(&conn));
    } else
    {   fprintf(stderr, "Successfully connected to Database.\n");
        int status = mysql_query(&conn, "SELECT * FROM users");
        res_set = mysql_store_result(&conn);
        int count = mysql_num_rows(res_set);
        printf("No of rows = %d\n", count);
        while ((row = mysql_fetch_row(res_set)) != NULL)
        {   for (int i = 0; i < mysql_num_fields(res_set); i++)
            {   printf("%s \t", row != NULL ? row : "NULL");
            } printf("\n");
        }
    }
    mysql_close(&conn);
 // getchar();
    return 0;
}

我发现有趣的是,如果我将 sprintf_s() 放在上面 mysql_init() 工作得很好吗?那么这是否意味着我需要对每个请求打开一个新连接?因为在 5.7 版本中它不能以这种方式工作,我可以建立连接然后执行多个语句。任何回复将不胜感激,因为我已经为此苦苦挣扎了一段时间......

以下是当 sprintf_s() 包含在编译中时调试器在调用 mysql_num_rows() 时抛出的异常...

ConsoleApplication1.exe 中的 0x00007FFED78550C0 (libmysql.dll) 引发异常:0xC0000005:读取位置 0x0000000000000000 时发生访问冲突。

因此,我将其精简为尽可能少的行以重现错误:

int main()
{   MYSQL conn;
    MYSQL_RES *res_set;

    mysql_init(&conn);

    char str[50];
    strcpy_s(str, "test");

    if (mysql_real_connect(&conn,"localhost","user","pass","db",0,NULL,0))
    {   int status = mysql_query(&conn, "SELECT * FROM users");
        res_set = mysql_store_result(&conn);
        int count = mysql_num_rows(res_set);  // Exception is thrown here.
    }
    mysql_close(&conn);
}

现在为什么会发生这种情况?谢谢,布莱恩..

最佳答案

您没有检查任何行字段是否为 NULL

使用代替

while ((row = mysql_fetch_row(res_set)) != NULL)
{ for (int i = 0; i < mysql_num_fields(res_set); i++)
  {
    printf("%s ", row[i] ? row[i] : "NULL");  
  } 
  printf("\n");
}

关于c++ - 在 MySql 中使用字符串操作函数会出现什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58664597/

相关文章:

c++ - 从未排序的数组中删除重复项

c# - 您如何处理从编写托管代码到非托管代码的过程?

php - 表单提交后生成引用ID

php - 如何在php中将文件从一个页面发送到另一个页面

windows - 错误由于错误而停止(org.apache.kafka.connect.cli.ConnectStandalone)java.lang.NoClassDefFoundError : io/debezium/util/IoUtil

C++:参数传递 "passed by reference"

c++ - 使用 Python 删除 C 和 C++ 注释?

Mysql - 逆 3 表查询

Windows 批处理文件 - 显示所有子文件夹

windows - tnsping ping 失败,即使我可以成功连接到数据库