c++ - 将 C++ 与 MySql 一起使用 : segmentation fault

标签 c++ mysql segmentation-fault

我正在尝试使 C++ 与 MySql 一起工作 我已经从链接中测试了以下代码

https://www.raspberrypi.org/forums/viewtopic.php?t=31394&p=272288

    #include <iostream>
#include <mysql/mysql.h> // I added include /usr/include/mysql/ to ld.so.conf which is why that works

using namespace std;

MYSQL *connection, mysql;
MYSQL_RES *result;
MYSQL_ROW row;
int query_state;

#define HOST "localhost" // you must keep the quotes on all four items,  
#define USER "root" // the function "mysql_real_connect" is looking for a char datatype,
#define PASSWD "123" // without the quotes they're just an int.
#define DB "temps"

int main()
{
//initialize database connection
    mysql_init(&mysql);

// the three zeros are: Which port to connect to, which socket to connect to 
// and what client flags to use.  unless you're changing the defaults you only need to put 0 here
    connection = mysql_real_connect(&mysql,HOST,USER,PASSWD,DB,0,0,0); 
// Report error if failed to connect to database
    if (connection == NULL) {
        cout << mysql_error(&mysql) << endl;
        return 1;
    }
//Send query to database
        query_state = mysql_query(connection, "select * from temps");
// store result
        result = mysql_store_result(connection);
       while ( ( row = mysql_fetch_row(result)) != NULL ) {
// Print result, it prints row[column_number])
        cout << row[0] << "\t" << row[1] << endl;
        }
    return 0;
}

文件编译成功:

g++ -o sqlOut -lmysqlclient sqlTest.cpp

但我得到了错误: 尝试运行编译后的文件时出现段错误!!!
任何帮助将不胜感激,谢谢

注意:我需要将我的 C++ 文件中的数据保存到 MySql 数据库中,并使用 phpMyAdmin 查看它,如果你给我另一个链接 aor turtorial to foollow 将非常有帮助

我正在使用树莓派 b+

最佳答案

您应该检查 row[0]row[1] 是否包含值(不是 NULL)。 试试这个:

while ( ( row = mysql_fetch_row(result)) != NULL ) {
  if(!row[0] || !row[1]){
    continue;
  }
  cout << row[0] << "\t" << row[1] << endl;
}

关于c++ - 将 C++ 与 MySql 一起使用 : segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918047/

相关文章:

c++ - Boost 1.57 Boost.Context fcontext_t 资源管理

用 auto 定义的变量的 C++11 类型

c++ - 在 C++ 中,多个线程对数组的各个单元格的修改是安全的(boost)

java - Android 中如何获取最后插入的记录?

mysql - 如何在 query_posts 的自定义字段上添加 order by

c++ - 如何调试段错误?

C 列表插入程序 - 运行时出现段错误

c++ - GetProcAddress() 失败,错误 127

mysql - 这是在 mysql 中制作一对一关系表的好习惯吗?

c - 分段故障 ? C