Linux 環境 C語言 操作MySql 的接口范例

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

 接上一小節,本來是計劃這一節用來講數據庫的增刪改查,但是在實現的過程中,出現了一點小問題,也不是技術的問題,就是在字符界面上比較不好操作。比如要注冊一個帳號,就需要弄個字符界面提示,然后輸入數字表示選擇,在依次輸入信息。(這一點,用C寫過什么管理系統就知道,很是麻煩。)考慮到本程序講的是網絡編程,就不弄增刪改查了,就判斷一個用戶名密碼是否正確就行了。

  首先是安裝mysql和創建數據庫,所用到的命令如下:

1 su root  //使用root用戶
2 yum install mysql-devel*
3 yum install mysql-server*
4 service mysqld start

  創建一個users數據庫和一個client表

復制代碼
1 $mysql -u root
2 mysql> create database users; 
3 mysql> use users;    //切換到users數據庫中
4 mysql> create table clients(id int,username varchar(32),password varchar(32) ); //創建一個叫test的表
5 mysql> show create table clients;  //顯示剛才創建的表信息
6 mysql> select * from clients;   //查詢client表中數據
7 mysql> quit
復制代碼

  1.插入數據

復制代碼
 1 #include <stdio.h>
 2 #include <mysql.h>
 3 #include <stdlib.h>
 4 
 5 #define HOST "localhost"
 6 #define USERNAME "root"
 7 #define PASSWORD ""
 8 #define DATABASE "users"
 9 
10 int main(int argc,char *argv[])
11 {
12     MYSQL conn;
13     int res;
14     char *sql="insert into clients values('1','user1','123456');";
15     mysql_init(&conn);
16 
17     if(mysql_real_connect(&conn,HOST,USERNAME,PASSWORD,DATABASE,0,NULL,CLIENT_FOUND_ROWS))
18     {
19         printf("Connect Success!\n");
20         res=mysql_query(&conn,sql);
21         if(res)
22         {
23             printf("Insert Error!\n");
24         }
25         else
26         {
27             printf("Insert Success!\n");
28         }
29     }
30     else
31     {
32         printf("Connect Failed!\n");
33         exit(-1);
34     }
35     return 0;
36 }
復制代碼

  2.刪除數據

復制代碼
 1 #include <stdio.h>
 2 #include <mysql.h>
 3 #include <stdlib.h>
 4 
 5 #define HOST "localhost"
 6 #define USERNAME "root"
 7 #define PASSWORD ""
 8 #define DATABASE "users"
 9 
10 int main(int argc,char *argv[])
11 {
12     MYSQL conn;
13     int res;
14     char *sql="delete from clients where username=\"user1\";";
15 
16     mysql_init(&conn);
17 
18     if(mysql_real_connect(&conn,HOST,USERNAME,PASSWORD,DATABASE,0,NULL,CLIENT_FOUND_ROWS))
19     {
20         printf("Connect Success!\n");
21         res=mysql_query(&conn,sql);
22         if(res)
23         {
24             printf("Delete Error!\n");
25         }
26         else
27         {
28             printf("Delete Success!\n");
29         }
30     }
31     else
32     {
33         printf("Connect Failed!\n");
34         exit(-1);
35     }
36     return 0;
37 }
復制代碼

  3.修改數據

復制代碼
 1 #include <stdio.h>
 2 #include <mysql.h>
 3 #include <stdlib.h>
 4 
 5 #define HOST "localhost"
 6 #define USERNAME "root"
 7 #define PASSWORD ""
 8 #define DATABASE "users"
 9 
10 int main(int argc,char *argv[])
11 {
12     MYSQL conn;
13     int res;
14     char *sql="update clients set username=\"user2\" where username=\"user1\";";
15     mysql_init(&conn);
16 
17     if(mysql_real_connect(&conn,HOST,USERNAME,PASSWORD,DATABASE,0,NULL,CLIENT_FOUND_ROWS))
18     {
19         printf("Connect Success!\n");
20         res=mysql_query(&conn,sql);
21         if(res)
22         {
23             printf("Update Error!\n");
24         }
25         else
26         {
27             printf("Update Success!\n");
28         }
29     }
30     else
31     {
32         printf("Connect Failed!\n");
33         exit(-1);
34     }
35     return 0;
36 }
復制代碼

  4.查詢數據

復制代碼
 1 #include <stdio.h>
 2 #include <mysql.h>
 3 #include <stdlib.h>
 4 
 5 #define HOST "localhost"
 6 #define USERNAME "root"
 7 #define PASSWORD ""
 8 #define DATABASE "users"
 9 
10 int main(int argc,char *argv[])
11 {
12     MYSQL conn;
13     MYSQL_RES *res_ptr;//指向查詢結果的指針
14     MYSQL_FIELD *field;//字段結構體指針
15     MYSQL_ROW result_row;//按行返回的查詢信息
16 
17     int res;
18     int i,j;
19     int row,column;//查詢返回的行數和列數
20     char *sql="select * from clients;";
21     mysql_init(&conn);
22 
23 
24     if(mysql_real_connect(&conn,HOST,USERNAME,PASSWORD,DATABASE,0,NULL,CLIENT_FOUND_ROWS))
25     {
26         printf("Connect Success!\n");
27         res=mysql_query(&conn,sql);
28         //res=0表示查詢成功
29         if(res)
30         {
31             printf("Select Error!\n");
32         }
33         else
34         {
35             printf("Select Success!\n");
36             //將查詢的結果給res_ptr
37             res_ptr=mysql_store_result(&conn);
38             //如果結果不為空,就可以輸出了
39             if(res_ptr)//可以用這個的真假來判斷用戶名密碼是否正確
40             {
41                 //有結果了
42                 column=mysql_num_fields(res_ptr);//獲取列數
43                 row=mysql_num_rows(res_ptr)+1;//加1是因為第一行是字段名
44                 printf("查詢到的數據有 %d 行\n",row);
45 
46                 //輸出結果的字段名
47                 for(i=0;field=mysql_fetch_field(res_ptr);i++)
48                 {
49                     printf("%s\t",field->name);
50                 }
51                 printf("\n");
52                 //按行輸出結果
53                 for(i=1;i<row;i++)
54                 {
55                     result_row=mysql_fetch_row(res_ptr);
56                     for(j=0;j<column;j++)
57                     {
58                         printf("%s\t",result_row[j]);
59                     }
60                     printf("\n");
61                 }
62             }
63             else
64             {
65                 //沒有結果
66                 printf("沒有查詢到匹配的數據。");
67             }
68         }
69     }
70     else
71     {
72         printf("Connect Failed!\n");
73         exit(-1);
74     }
75     mysql_close(&conn);
76     return 0;
77 }
復制代碼

  對應的makefile

1 main:
2         gcc insert.c `mysql_config --cflags --libs` -o insert
3         gcc delete.c `mysql_config --cflags --libs` -o delete
4         gcc update.c `mysql_config --cflags --libs` -o update
5         gcc select.c `mysql_config --cflags --libs` -o select

  由于本次的重點不是數據庫的操作,所以就簡單的給出常用的基本方法,在我們的聊天程序中只加入查詢用戶密碼的功能,其他的如注冊用戶什么的就不寫了,應該沒有什么難度,就是有點煩。

  加入數據庫連接后的聊天程序

  client.c 不變

  server.c 修改如下

復制代碼
  ... 
 17 #include <mysql.h>//用于mysql連接
 18 ... 
37
38 void print_time(char * ch,time_t *now) 39 { 40 struct tm*stm; 41 stm=localtime(now);//立即獲取當前時間 42 sprintf(ch,"%02d:%02d:%02d\n",stm->tm_hour,stm->tm_min,stm->tm_sec); 43 } 44 45 int mysql_check_login(struct user su) 46 { 47 MYSQL conn; 48 MYSQL_RES *res_ptr; 49 int res; 50 int row; 51 char sql[256]={0}; 52 strcpy(sql,"select * from clients where username=\""); 53 strcat(sql,su.name); 54 strcat(sql,"\" and password=\""); 55 strcat(sql,su.pwd); 56 strcat(sql,"\";"); 57 printf("查詢的sql:%s\n",sql); 58 59 mysql_init(&conn); 60 if(mysql_real_connect(&conn,"localhost","root","","users",0,NULL,CLIENT_FOUND_ROWS)) 61 { 62 res=mysql_query(&conn,sql); 63 if(res) 64 { 65 perror("Select SQL Error!\n"); 66 exit(-1); 67 } 68 else 69 { 70 res_ptr=mysql_store_result(&conn); 71 if(res_ptr) 72 { 73 row=mysql_num_rows(res_ptr); 74 if(row==0) 75 return 0; 76 return 1;//1表示驗證成功 77 } 78 else 79 { 80 return 0;//0表示驗證失敗 81 } 82 } 83 } 84 else 85 { 86 perror("Database Connect Failed!"); 87 exit(-1); 88 } 89 mysql_close(&conn); 90 return 0; 91 } 92 93 int main(int argc,char *argv[]) 94 {...
110 struct timeval timeout; 111 struct user use; 112 time_t now; struct tm *timenow; 113 ... 168 while(1) 169 {... 174 switch(select(max_servfd+1,&servfd,NULL,NULL,&timeout)) 175 { 176 case -1: 177 perror("select error"); 178 break; 179 case 0: 180 break; 181 default: 182 //printf("has datas to offer accept\n"); 183 if(FD_ISSET(sockfd,&servfd))//sockfd 有數據表示可以進行accept 184 {   ...
200 printf("客戶端發來的用戶名是:%s,密碼:%s\n",use.name,use.pwd); 201 memset(recvBuf,0,sizeof(recvBuf)); 202 if(mysql_check_login(use)) 203 { 204 printf("驗證成功!\n"); 205 strcpy(sendBuf,"yes"); 206 } 207 else 208 { 209 printf("驗證失敗!\n"); 210 strcpy(sendBuf,"no"); 211 } 212 if((sendSize=send(clientfd,sendBuf,MAX_DATA_SIZE,0))==-1) 213 { 214 perror("fail to receive datas"); 215 }...
221 } 222 break; 223 } 224 //FD_COPY(recvfd,servfd); 225 for(i=0;i<MAX_CON_NO;i++)//最大隊列進行判斷,優化的話,可以使用鏈表 226 {...
231 } 232 233 switch(select(max_recvfd+1,&recvfd,NULL,NULL,&timeout)) 234 {...
288 } 289 } 290 return 0; 291 }
復制代碼

?  本次就增加了一個mysql_check_login這個函數用于用戶名和密碼的判斷。也沒有加入太多的功能。只要有個大概思路就可以了,剩下的注冊和修改基本相似,就不加入到程序中了。

  接下來還是老規矩,上一張運行時的截圖

  數據庫中的用戶名是user1,密碼是123456。看,完成了驗證了。頓時感覺好極了。

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/384168.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/384168.shtml
英文地址,請注明出處:http://en.pswp.cn/news/384168.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

二進制邏輯運算符有關練習題

//1.寫一個函數返回參數二進制中 1 的個數 #include<stdio.h> int div 0; //除數 int rem 0; //余數 int count 0; //計1 int count_one_bits(unsigned int div) {int con 0; //商while (div > 1){con div / 2;rem div % 2;div con;if (1 rem){count;}}…

Catch That Cow——BFS

【題目描述】 Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer Jo…

利用mysql提供的c語言接口操作數據庫

http://blog.csdn.net/bladeandmaster88/article/details/52980872 //1.工程要在c/c->常規->附加包含目錄添加mysql.h的路徑D:\mysql5.5\include //2.工程要在鏈接器->常規->附加庫目錄添加libmysql.lib的路徑D:\mysql5.5\lib #include <WinSock2.h>/…

數組相關運算

數組的初始化 數組及指針在內存中的存儲 一維數組在內存中的存儲 有關數組的運算 //一維數組 int a[] {1,2,3,4}; printf("%d\n",sizeof(a));//16這里的a表示的是整個數組,計算出的是整個數組的大小,單位為byte printf("%d\n",sizeof(a 0));/*a沒有單獨…

Find The Multiple——簡單搜索+大膽嘗試

【題目描述】 Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more t…

C語言操作MYSQL小例子

http://blog.csdn.net/small_qch/article/details/8180678 初學使用用C語言操作MYSQL&#xff0c;寫了個小例子&#xff0c;帖上來獻丟人一下&#xff0c;呵呵。 程序很簡單&#xff0c;先連接數據庫&#xff0c;然后向class1表中插入一條數據&#xff0c;最后獲取并輸出整個cl…

Find a way——BFS

【題目描述】 Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki. Yifenfei’s home is at the countryside, but Merceki’s home is in the ce…

用C語言操作MySQL數據庫

http://blog.chinaunix.net/uid-26743670-id-3479887.html 參考MYSQL的幫助文檔整理 這里歸納了C API可使用的函數&#xff0c;并在下一節詳細介紹了它們。請參見25.2.3節&#xff0c;“C API函數描述”。 函數 描述 mysql_affected_rows() 返回上次UPDATE、DELETE或INSERT查…

三字棋

整個游戲可以分為以下幾個環節 1.打印一個玩游戲的菜單 2.玩游戲 (1)玩家走一步 (2)電腦走一步 每走一步對結果進行顯示,其中游戲的結果可分為玩家贏,電腦贏,以及平局 代碼顯示如下 game.c #define _CRT_SECURE_NO_WARNINGS 1 #include<stdlib.h> #include<stdio.h&…

gets fgets 區別

http://www.cnblogs.com/aexin/p/3908003.html 1. gets與fgets gets函數原型&#xff1a;char*gets(char*buffer);//讀取字符到數組&#xff1a;gets(str);str為數組名。 gets函數功能&#xff1a;從鍵盤上輸入字符&#xff0c;直至接受到換行符或EOF時停止&#xff0c;并將讀取…

Fliptile——搜索+二進制優化

【題目描述】 Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M N grid (1 ≤ M ≤ 15; 1 ≤ N ≤ 15) of square tiles, each of which is col…

掃雷

1.將掃雷界面看成一個二維數組,先對界面進行打印 2.置雷 3.排雷 4.對每次的結果進行游戲輸出 5.提醒用戶游戲輸贏 game.c #define _CRT_SECURE_NO_WARNINGS 1 #include"game.h" //初始化 void init_board(char mine[ROWS][COLS], int rows, int cols, char set) {in…

C相關練習題

1.調整數組使奇數全部都位于偶數前面。 輸入一個整數數組&#xff0c;實現一個函數&#xff0c;來調整該數組中數字的順序使得數組中所有的奇數位于數組的前半部分&#xff0c;所有偶數位于數組的后半部分。 #include<stdio.h> void range(int arr[], int sz) {int left…

【C語言】單鏈表的所有操作的實現(包括PopBack、PushBack、PopFront、PushFront、Insert)

http://blog.csdn.net/hanjing_1995/article/details/51539563 [cpp] view plaincopy #define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; //單鏈表的實現 #include<assert.h> typedef int DataType; typedef…

Shuffle'm Up——簡單模擬

【題目描述】 A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuffling chips is performed by starting with two stacks of poker chips, S1 and S2, each stack containing C chips. Each stack may contain chips of several diff…

C++ explicit關鍵字詳解

http://www.cnblogs.com/ymy124/p/3632634.html 首先, C中的explicit關鍵字只能用于修飾只有一個參數的類構造函數, 它的作用是表明該構造函數是顯示的, 而非隱式的, 跟它相對應的另一個關鍵字是implicit, 意思是隱藏的,類構造函數默認情況下即聲明為implicit(隱式). 那么顯示聲…

Fire!——兩個BFS

【題目描述】 【題目分析】 看到題目后很清楚是兩個BFS&#xff0c;可是我覺得對于火的BFS可以轉換成判斷&#xff0c;我的做法是將火的位置全部記錄下來&#xff0c;然后判斷某個位置距離每個火的步數是否小于當前步數&#xff0c;可是錯了&#xff0c;還不清楚為什么&#x…

函數調用過程(棧楨)

棧楨 首先來看一段代碼 #include<stdio.h> int add(int x, int y) {int z x y;return z; } int main() {int a 10;int b 20;int ret add(a, b);printf("ret %d\n",ret);return 0; } 此處是為了給a,b分別開辟空間,這時棧楨如圖所示 兩條push命令將a,b變…

C++智能指針簡單剖析

http://blog.csdn.net/lanxuezaipiao/article/details/41603883 導讀 最近在補看《C Primer Plus》第六版&#xff0c;這的確是本好書&#xff0c;其中關于智能指針的章節解析的非常清晰&#xff0c;一解我以前的多處困惑。C面試過程中&#xff0c;很多面試官都喜歡問智能指針相…

非常可樂——BFS

【題目描述】 大家一定覺的運動以后喝可樂是一件很愜意的事情&#xff0c;但是seeyou卻不這么認為。因為每次當seeyou買了可樂以后&#xff0c;阿牛就要求和seeyou一起分享這一瓶可樂&#xff0c;而且一定要喝的和seeyou一樣多。但seeyou的手中只有兩個杯子&#xff0c;它們的容…