Mar 13

Linux下C语言处理MySQL数据库示例程序 不指定

felix021 @ 2009-3-13 09:41 [IT » 数据库] 评论(0) , 引用(0) , 阅读(6568) | Via 本站原创 | |
花了n久的时间终于搞清楚了,丫丫的,真麻烦

编译:
引用
g++ -Imysql/include -Lmysql/lib -o a.out a.cpp -lmysqlclient -lz

这个mysql目录是某个mysql的源码目录,如果有安装mysql-devel可能是在/usr/ooxx/mysql,没有的话自己去down源码

#include<iostream>
#include<string>
#include<fstream>
#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;
}




欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]