c++ - MySQL C API 为 NULL 值返回零而不是 NULL

标签 c++ mysql sql database

我们正试图从文件中获取数据并将其插入具有这种表格式的 mysql 表中。然后稍后检索数据并将其放回与原始文件中数据相同的格式。这就是我们创建表的方式。

create_query = "CREATE TABLE IF NOT EXISTS ";
string date = "20170223";
string table_format = " (IDpk INT NOT NULL auto_increment,"
                      " symbol CHAR(8) NOT NULL,"
                      " number_1 BIGINT unsigned DEFAULT NULL,"
                      " number_2 BIGINT unsigned NOT NULL,"
                      " PRIMARY KEY(IDpk))";

这就是我们创建要插入数据库的字符串的方式。

 uint32_t item_type = stoi(tokens[2]);
      query = insert_query;

      switch(item_type)
      {
        case 0: //bid
        case 1: //ask
        {           "###,%s,%s,"
                    "NULL,"
                    "%s,%s",
                    tokens[0], tokens[1], tokens[2]);
          break;
        }

然后我们将数据传递给这个函数,我们实际上是将数据插入到表中。

void read_in_data(string date, string file, MYSQL* conn)
{
string query = "LOAD DATA INFILE " + file +
              "INTO TABLE " + date +
              "FIELDS TERMINATED BY ','"
              "LINE STARTING BY '###'";

mysql_query(conn, query.c_str());
}

当我们稍后尝试从数据库中取回数据并将其重新格式化为类似于原始输入文件时,就会出现问题。我们注意到我们的 NULL 值由 0 而不是 NULL 表示。我们很好奇如何插入它们以使它们为 NULL 而不是 0。这是我们当前的提取方法。

ofstream out_file;
out_file.open("test.txt", fstream::in);
if(out_file.good())
{
  res = mysql_store_result(conn);
  int num_fields = mysql_num_fields(res);
  while((row = mysql_fetch_row(res)))
  {
    unsigned long * lengths;
    lengths = mysql_fetch_lengths(res);
    for(int i = 0; i < num_fields; i++)
    {
      if(row[i])
      {
        out_file << row[i] << " ";
      }
    }
    out_file << endl;
  }
}else
cout << strerror(errno) << endl;

最佳答案

对于NULL值,你需要从结果中检查is_null,我相信MYSQL_BIND结构。

由于在您的情况下您使用的是 mysql_fetch_row()I recommend reading this

The number of values in the row is given by mysql_num_fields(result). If row holds the return value from a call to mysql_fetch_row(), pointers to the values are accessed as row[0] to row[mysql_num_fields(result)-1]. NULL values in the row are indicated by NULL pointers.

如你所见,问题在于这是一个c库,而c++中的NULL定义为0*,所以就是为什么数据库中的 NULL 值得到 0

解决此问题的唯一方法是使用列类型的知识来确定它是 0(integer)还是 NULL 值,但对于 NULL 整数值,您无法知道它。

如果可以,使用准备好的语句并测试 MYSQL_BIND 结构的 is_null 成员,或者用 c 编写整个东西,因为这是一个 c 库。


*我认为这就是为什么较新的标准创建了 nullptr

关于c++ - MySQL C API 为 NULL 值返回零而不是 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42844816/

相关文章:

c++ - 使用 __uuidof 运算符会给出扩展使用警告

c++ - 在循环中初始化一个数组

c++ - C++ 中的模板 lambda 表达式

php - 一个html表中的双重查询[PHP/mysql]

sql - 锁定多行

c++ - 从CreateProcess调用c中的msi文件

php - 找出保存项目的表名 - opencart

mysql - 在可能包含 NULL 的列上加入

c# - SQL 查询从 BIT 类型列中获取 boolean 值

sql - 计算表列中值的变化