mysql.lib 的使用

一 说明
      mysql.lib 提供了很多方便的操作,同时结合 vector 使用十分方便。

二 使用
    1 声明需要用到的变量

static MYSQL s_mysql[DATABASE_CONNECTION_NUM];
static char mysql_user[50]="root";
static char mysql_password[50]="";

  2 初始化数据库连接
初始化连接过程中,根据自己的需要,是否有包含中文字符,设置数据库的属性。

 1 bool InitDBConnetion()
 2 {
 3     int i = 0;
 4     bool bOK = false;
 5 
 6     for(i = 0;i < DATABASE_CONNECTION_NUM;i++)
 7     {
 8         mysql_init(&s_mysql[i]);
 9         mysql_options(&s_mysql[i], MYSQL_SET_CHARSET_NAME, "utf8");
10 
11         if(NULL == mysql_real_connect(&s_mysql[i], "localhost", mysql_user, mysql_password, DB_NAME, DB_PORT, NULL, 0))
12         {
13             printf("Failed to connect to database: Error: %s\n", mysql_error(&s_mysql[i]));
14             break;
15         }
16     }
17 
18     if(i < DATABASE_CONNECTION_NUM)
19     {
20         CloseDBConnection();
21     }
22     else
23     {
24         bOK = true;
25     }
26 
27     return bOK;
28 }
29 

  3 查询并保存结果

1 typedef struct
2 {
3     char chGroupName[256];
4     unsigned char uchGroupInternalId[4];
5     unsigned char uchGroupMemberNum[3];
6 
7 }GROUP_INFO;

  

1 static int GetUserGroupInfo(vector<GROUP_INFO> &vGroup, MYSQL *pMySqlConnection)
 2 {
 3     int groupNum = 0;
 4     MYSQL_RES *pResult = NULL;
 5     do 
 6     {
 7         char chSql[1024] ={0};
 8         sprintf(chSql, "select group_id,group_name from `cloudsoarmanage`.`user_group`");
 9         if (0 != mysql_query(pMySqlConnection,chSql))
10         {
11             break;
12         }
13 
14         pResult = mysql_store_result(pMySqlConnection);
15         if (NULL == pResult)
16         {
17             break;
18         }
19 
20         MYSQL_ROW sql_row;
21         int groupId = 0;
22         while (sql_row = mysql_fetch_row(pResult))
23         {
24             GROUP_INFO info = {0};
25             strcpy(info.chGroupName, sql_row[1]);
26             groupId = atoi(sql_row[0]);
27             info.uchGroupInternalId[0] = groupId & 0xFF;
28             info.uchGroupInternalId[1] = (groupId>>8) & 0xFF;
29             info.uchGroupInternalId[2] = (groupId>>16) & 0xFF;
30             info.uchGroupInternalId[3] = (groupId>>24) & 0xFF;
31             vGroup.push_back(info);
32             ++groupNum;
33         }
34 
35     } while (0);
36 
37     if (NULL != pResult)
38     {
39         mysql_free_result(pResult);
40     }
41 
42     return groupNum;
43 }

  

1 void CloseDBConnection()
2 {
3     int i = 0;
4 
5     for(i = 0; i < DATABASE_CONNECTION_NUM; i++)
6     {
7         mysql_close(&s_mysql[i]);
8     }
9 }

  

转载于:https://www.cnblogs.com/zhiyewang/p/5208958.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值