C++调用MySql

参考了下面两个博客:

http://www.cnblogs.com/wunaozai/p/3618383.html

http://zhmy.michael.blog.163.com/blog/static/861578792012101244715692/

1. 首先安装C/C++ API:

sudo apt-get install mysql-server libmysql++-dev

2. 将lib文件拷到公用文件夹:
sudo cp /usr/lib/mysql/* /usr/lib/

3. 写好C++代码test.cpp,功能是更改数据库yg_sql中yg_user_images表中的score 

#include <iostream>
#include <mysql/mysql.h>

using namespace std;

int main(int argc,char *argv[])
{
    MYSQL conn;
    int res;
    mysql_init(&conn);
    //222555yq为数据库的进入密码,yg_sql为数据库名
    if(mysql_real_connect(&conn,"localhost","root","222555yq","yg_sql",0,NULL,CLIENT_FOUND_ROWS)) 
    {
         cout << "connect success!" << endl;
         //将数据库yg_user_images表中字段id为1所对应字段score的数据修改为100
         res=mysql_query(&conn,"update yg_user_images set score = '100' where id = '1'"); 
         //判断是否读取成功
         if(res)
             cout << "error" << endl;
         else
             cout << "OK" << endl;
         mysql_close(&conn);
    }
    return 0;
}

 

4. 然后编译:

g++ test.cpp `mysql_config --cflags --libs` -o test

5. 执行:

./test

再次查看数据库发现数据库中对应的score值被修改了

 

C++读取数据库某个字段数据的代码如下:

#include <iostream>
#include <string>
#include <mysql/mysql.h>

using namespace std;

int main(int argc,char *argv[])
{
    MYSQL conn;
    int res;
    MYSQL_RES *result = NULL;
    MYSQL_FIELD *field = NULL;
    mysql_init(&conn);
    //222555yq为数据库的进入密码,yg_sql为数据库名
    if(mysql_real_connect(&conn,"localhost","root","222555yq","yg_sql",0,NULL,CLIENT_FOUND_ROWS)) 
    {
         cout << "connect success!" << endl;
         res = mysql_query(&conn,"select img_url from yg_user_images"); //读取数据库yg_sql的yg_user_images表中图片路径字段下的数据(路径)
         //判断是否读取成功
         if(res)
             cout << "error" << endl;
         else
             cout << "OK" << endl;
         //保存结果    
         result = mysql_store_result(&conn);
         //路径数据的个数
         int rowcount = mysql_num_rows(result);
         cout << rowcount << endl;
         //字段的个数
         int fieldcount = mysql_num_fields(result);
         cout << fieldcount << endl;
         //显示所有字段
         for(int i = 0; i < fieldcount; i++)
         {
             field = mysql_fetch_field_direct(result,i);
             cout << field->name << "\t\t";
         }
         cout << endl;
         //显示各个字段下的所有数据
         MYSQL_ROW row = NULL;
         row = mysql_fetch_row(result);
         while(NULL != row)
         {
             for(int i=0; i<fieldcount; i++)
             {
                 cout << row[i] << "\t\t"; 
             }
             cout << endl;
             row = mysql_fetch_row(result);
         }
         mysql_close(&conn);
    }
    return 0;
}

按照上面步骤编译运行,会打印出如下结果:

 

posted @ 2017-11-02 10:31  YYYYQQQQ  阅读(5215)  评论(0编辑  收藏  举报