一 说明
mysql.lib 提供了很多方便的操作,同时结合 vector 使用十分方便。
二 使用
1 声明需要用到的变量
1 static MYSQL s_mysql[DATABASE_CONNECTION_NUM];
2 static char mysql_user[50]="root";
3 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 }