C++操作mysql__通過mysql的c api連接mysql服務器


C++通過mysql的c api連接mysql服務器

1、在連接之前,不要忘記打開mysql服務器哇(Navicat打開或者不打開都可以)

2、添加包含目錄

3、添加libmysql.lib到附屬依賴中

上一步中也也可以在程序代碼的開始處加上#pragma comment(lib,"D:\\Program Files\\MySQL\\MySQL Server 5.6\\lib\\libmysql.lib") 來導入libmysql.lib)

4、如果使用的mysql是64位的,還需要將項目的解決方案平台由win32改成x64

 

5、將D:\Program Files\MySQL\MySQL Server 5.6\lib(根據具體路徑而定)下的libmysql.dll復制到項目中去,和.cpp,.h文件位於同一路徑下

 實例代碼:

 1 #include <stdio.h>
 2 #include <mysql.h> // 如果配置ok就可以直接包含這個文件
 3 int main(void)
 4 {
 5     MYSQL mysql;    //一個數據庫結構體
 6     MYSQL_RES* res; //一個結果集結構體
 7     MYSQL_ROW row;  //char** 二維數組,存放一條條記錄
 8                     
 9     mysql_init(&mysql);//初始化數據庫
10     //設置編碼方式
11     mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gbk");
12     //連接數據庫
13     //判斷如果連接失敗就輸出連接失敗。
14     if (mysql_real_connect(&mysql, "localhost", "root", "123456", "mysql", 3306, NULL, 0) == NULL)  //mysql是一個數據庫
15         printf("連接失敗!\\n");
16     //查詢數據
17     mysql_query(&mysql, "select * from db");  //db是數據庫下的一個表
18     //獲取結果集
19     res = mysql_store_result(&mysql);
20 
21     //給ROW賦值,判斷ROW是否為空,不為空就打印數據。
22     while (row = mysql_fetch_row(res))
23     {
24         printf("%s  ", row[0]);//打印ID      打印第一列
25         printf("%s  ", row[1]);//打印姓名    打印第二列
26         printf("%s  ", row[2]);//            打印第三列
27         printf("%s  ", row[3]);
28         printf("%s  ", row[4]);
29         printf("%s  ", row[5]);
30         printf("%s  \n", row[6]);
31     }
32     //釋放結果集
33     mysql_free_result(res);
34     //關閉數據庫
35     mysql_close(&mysql);
36     //停留等待
37     system("pause");
38     return 0;
39 }
View Code

Navicat中的信息:

 

C++通過mysql的c api連接mysql服務器,並對數據庫中的內容進行增刪修改操作

在上面操作的基礎上,修改代碼如下:

  1 #include <stdio.h>
  2 #include <WinSock.h>  //一定要包含這個,或者winsock2.h
  3 //#include "include/mysql.h"    //引入mysql頭文件(一種方式是在vc目錄里面設置,一種是文件夾拷到工程目錄,然后這樣包含)
  4 #include "mysql.h"  
  5 #include <Windows.h>
  6 
  7 //包含附加依賴項,也可以在工程--屬性里面設置
  8 #pragma comment(lib,"wsock32.lib")
  9 #pragma comment(lib,"libmysql.lib")
 10 MYSQL mysql; //mysql連接
 11 MYSQL_FIELD *fd;  //字段行數組
 12 char field[32][32];  //存字段名二維數組
 13 MYSQL_RES *res; //這個結構代表返回行的一個查詢結果集
 14 MYSQL_ROW column; //一個行數據的類型安全(type-safe)的表示,表示數據行的列
 15 char query[150]; //存放mysql查詢語句
 16 
 17 bool ConnectDatabase();     //函數聲明
 18 void FreeConnect();
 19 bool QueryDatabase1();  //查詢1
 20 bool QueryDatabase2();  //查詢2
 21 bool InsertData();
 22 bool ModifyData();
 23 bool DeleteData();
 24 
 25 int main(int argc, char **argv)
 26 {
 27     ConnectDatabase();
 28     QueryDatabase1();
 29     InsertData();
 30     QueryDatabase2();
 31     ModifyData();
 32     QueryDatabase2();
 33     DeleteData();
 34     QueryDatabase2();
 35     FreeConnect();
 36     system("pause");
 37     return 0;
 38 }
 39 //連接數據庫
 40 bool ConnectDatabase()
 41 {
 42     //初始化mysql
 43     mysql_init(&mysql);  //連接mysql,數據庫
 44 
 45     //返回false則連接失敗,返回true則連接成功
 46     if (!(mysql_real_connect(&mysql, "localhost", "root", "123456", "test", 0, NULL, 0))) //中間分別是主機,用戶名,密碼,數據庫名,端口號(可以寫默認0或者3306等),可以先寫成參數再傳進去
 47     {
 48         printf("Error connecting to database:%s\n", mysql_error(&mysql));
 49         return false;
 50     }
 51     else
 52     {
 53         printf("Connected...\n");
 54         return true;
 55     }
 56 }
 57 //釋放資源
 58 void FreeConnect()
 59 {
 60     //釋放資源
 61     mysql_free_result(res);
 62     mysql_close(&mysql);
 63 }
 64 /***************************數據庫操作***********************************/
 65 //其實所有的數據庫操作都是先寫個sql語句,然后用mysql_query(&mysql,query)來完成,包括創建數據庫或表,增刪改查
 66 //查詢數據
 67 //int sprintf(char* str,const char* format,...) 發送格式化輸出到str所指向的字符串
 68 bool QueryDatabase1()
 69 {
 70     sprintf(query, "select * from user"); //執行查詢語句,這里是查詢所有,user是表名,不用加引號,用strcpy也可以
 71     mysql_query(&mysql, "set names gbk"); //設置編碼格式(SET NAMES GBK也行),否則cmd下中文亂碼
 72     //返回0 查詢成功,返回1查詢失敗
 73     if (mysql_query(&mysql, query))        //執行SQL語句
 74     {
 75         printf("Query failed (%s)\n", mysql_error(&mysql));
 76         return false;
 77     }
 78     else
 79     {
 80         printf("query success\n");
 81     }
 82     //獲取結果集
 83     if (!(res = mysql_store_result(&mysql)))    //獲得sql語句結束后返回的結果集
 84     {
 85         printf("Couldn't get result from %s\n", mysql_error(&mysql));
 86         return false;
 87     }
 88 
 89     //打印數據行數
 90     printf("number of dataline returned: %lld\n", mysql_affected_rows(&mysql));  //此處原本是%d但是會報錯,根據原因改成了%lld,lld表示長整形
 91 
 92     //獲取字段的信息
 93     char *str_field[32];  //定義一個字符串數組存儲字段信息
 94     for (int i = 0; i < 4; i++)   //在已知字段數量的情況下獲取字段名
 95     {
 96         str_field[i] = mysql_fetch_field(res)->name;
 97     }
 98     for (int i = 0; i < 4; i++)   //打印字段
 99         printf("%10s\t", str_field[i]);  //此處有個制表符\t
100     printf("\n");
101     //打印獲取的數據
102     while (column = mysql_fetch_row(res))   //在已知字段數量情況下,獲取並打印下一行
103     {
104         printf("%10s\t%10s\t%10s\t%10s\n", column[0], column[1], column[2], column[3]);  //column是列數組 每一個數據后面都有一個制表符,cout是沒有制表符的吧
105     }
106     return true;
107 }
108 bool QueryDatabase2()
109 {
110     mysql_query(&mysql, "set names gbk");
111     //返回0 查詢成功,返回1查詢失敗
112     if (mysql_query(&mysql, "select * from user"))        //執行SQL語句
113     {
114         printf("Query failed (%s)\n", mysql_error(&mysql));
115         return false;
116     }
117     else
118     {
119         printf("query success\n");
120     }
121     res = mysql_store_result(&mysql);
122     //打印數據行數
123     printf("number of dataline returned: %lld\n", mysql_affected_rows(&mysql));
124     for (int i = 0; fd = mysql_fetch_field(res); i++)  //獲取字段名
125         strcpy(field[i], fd->name);
126     int j = mysql_num_fields(res);  // 獲取列數
127     for (int i = 0; i < j; i++)  //打印字段
128         printf("%10s\t", field[i]);
129     printf("\n");
130     while (column = mysql_fetch_row(res))
131     {
132         for (int i = 0; i < j; i++)
133             printf("%10s\t", column[i]);
134         printf("\n");
135     }
136     return true;
137 }
138 //插入數據
139 bool InsertData()
140 {
141     sprintf(query, "insert into user values (6, 'Lilei', '123','lilei23@sina.cn');");  //可以想辦法實現手動在控制台手動輸入指令
142     if (mysql_query(&mysql, query))        //執行SQL語句
143     {
144         printf("Query failed (%s)\n", mysql_error(&mysql));  //可以檢查輸入的信息是否有錯誤,比如輸入的類型和字段的類型是否匹配
145         return false;
146     }
147     else
148     {
149         printf("Insert success\n");
150         return true;
151     }
152 }
153 //修改數據
154 bool ModifyData()
155 {
156     sprintf(query, "update user set email='lilei325@163.com' where name='Lilei'");
157     if (mysql_query(&mysql, query))        //執行SQL語句
158     {
159         printf("Query failed (%s)\n", mysql_error(&mysql));
160         return false;
161     }
162     else
163     {
164         printf("Modify success\n");
165         return true;
166     }
167 }
168 //刪除數據
169 bool DeleteData()
170 {
171     /*sprintf(query, "delete from user where id=6");*/
172     char query[100];
173     printf("please input the sql:\n");
174     gets_s(query);  //這里手動輸入sql語句
175     if (mysql_query(&mysql, query))        //執行SQL語句
176     {
177         printf("Query failed (%s)\n", mysql_error(&mysql));
178         return false;
179     }
180     else
181     {
182         printf("Delete success\n");
183         return true;
184     }
185 }
C++對數據庫中的數據做增刪修改操作

執行結果:

 參考博客:https://www.cnblogs.com/47088845/p/5706496.html#top


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM