时间:2021-07-01 10:21:17 帮助过:24人阅读
Linux下C语言处理MySQL数据库示例程序,花了n久的时间终于搞清楚了,丫丫的,真麻烦编译:引用g++ -Imysql/include -Lmysql/lib
Linux下C语言处理MySQL数据库示例程序,花了n久的时间终于搞清楚了,丫丫的,真麻烦
编译:
引用
g++ -Imysql/include -Lmysql/lib -o a.out a.cpp -lmysqlclient -lz
这个mysql目录是某个mysql的源码目录,,如果有安装mysql-devel可能是在/usr/ooxx/mysql,没有的话自己去down源码
#include
#include
#include
#include"mysql.h"
using namespace std;
MYSQL * conn = NULL; //MySQL连接句柄
//读取配置
bool read_conf(string &dbhost,
string &dbuser,
string &dbpass,
string &dbname){
ifstream is("judge.conf");
is >> dbhost >> dbuser >> dbpass >> dbname;
return true;
}
bool query(){
int status, state, state2;
MYSQL_RES * res;
MYSQL_ROW row;
string cmd;
MYSQL *conn, mysql;
string dbhost, dbuser, dbpass, dbname;
if(read_conf(dbhost,dbuser, dbpass, dbname)){ //读取数据库
if (mysql_init(&mysql) == NULL){
fprintf(stderr, "初始化错误\n");
return false;
}
conn = mysql_real_connect(&mysql, dbhost.c_str(), dbuser.c_str(),
dbpass.c_str(), dbname.c_str(), NULL,
"/var/run/mysqld/mysqld.sock", 0);
if(conn == NULL){ //连接失败
fprintf(stderr, "连接失败!\n");
return false;
}
}else{ //读取配置失败
fprintf(stderr, "读取配置失败!\n");
return false;
}
cmd = "SELECT OOXX FROM OOXX";
cout << "Command: " << cmd << endl;
state = mysql_query(conn, cmd.c_str());
cout << "state: " << state << endl;
if(state != 0){//查询出错
fprintf(stderr, "%s\n", mysql_error(conn));
return false;
}
res = mysql_store_result(conn);
cout << "affected_rows:" << conn->affected_rows << endl;
while(row = mysql_fetch_row(res), row != NULL){
printf("%s\n", row[0]);
}
return true;
}
int main(){
query();
return 0;
}
如果觉得这篇文章对你有用,请在下面留个言让我知道,非常感谢^_^
转载请注明出自 ?1505 (如是转载文则注明原出处),谢谢:)