我正在尝试使 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/