简单SQL代码上的分段错误(核心转储)

时间:2012-12-05 18:31:06

标签: c++ mysql ubuntu

我在一些简单的C ++代码上遇到“Segmentation fault(core dumped)”错误。当我使用变量结果时,错误将会发生。在这种情况下会出现什么问题?我知道有些东西超出了范围,但结果怎么可能呢?数据库中只有2个项目。

#include <iostream>
#include <boost/variant.hpp>
#include <mysql/mysql.h>
#include <mysql_connection.h>

using namespace std;

const char *server = "localhost";
const char *user = "XXXX";
const char *password = "XXXX";
const char *database = "XXXX";

int main()
{
    MYSQL *conn;
    MYSQL_RES *result;
    MYSQL_ROW row;

    int num_fields = 0;

    conn = mysql_init(NULL);
    mysql_real_connect(conn, server,user, password, database, 0, NULL, 0);

    mysql_query(conn, "SELECT * FROM `users` WHERE `id` = '5'");
    result = mysql_store_result(conn);

    num_fields = mysql_num_fields(result);

    while ((row = mysql_fetch_row(result)))
    {
       cout << "Spam ";
    }

    mysql_free_result(result);
    mysql_close(conn);
}

错误:

Segmentation fault (core dumped)

Process returned 139 (0x8B)   execution time : 0.255 s
Press ENTER to continue.

1 个答案:

答案 0 :(得分:0)

解决方案是创建一个符号链接,以便mysql可以找到mysql.sock:

sudo ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock