用c++配合MySql:分割故障

use C++ with MySql : segmentation fault

本文关键字:分割 故障 MySql c++ 配合      更新时间:2023-10-16

我正试图使一个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

但是我得到了错误:分段错误当试图运行编译文件!!
任何帮助将不胜感激,谢谢

NB:我需要保存数据从我的c++文件到MySql数据库,并查看它与phpMyAdmin,这将是非常有帮助的,如果你给我另一个链接或教程的傻瓜

我使用树莓PI 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;
}

我已经使用"temps"为数据库和表,我已经改变了表的名称

select * from "tempdat"

这里tempps是数据库名tempdat是表名=>它现在可以工作了

希望能帮助到有同样错误的人