使用C语言查询MySQL数据库简要示例
数据库:personal
表:contact
mysql> select * from contact;
+--------+----------------+--------+-------+------------+-----------------------------------------------------------------+
| name | email | tel | qq | birthday | note |
+--------+----------------+--------+-------+------------+-----------------------------------------------------------------+
| Petter | abc@gmail.com | 12345 | 54321 | 2008-11-14 | Loves sweet very much! |
| Marry | aa@163.com | 13456 | 65431 | 2008-03-05 | Hates Sanlu milk powder! |
| Jack | zz@163.net | 13221 | 3422 | 2007-10-02 | Has been in Heaven because of the magic powder mentioned above! |
| Rose | rr@hotmail.com | 343232 | 2321 | 2007-12-08 | Jack's lover. Suffering from the damn powder |
+--------+----------------+--------+-------+------------+-----------------------------------------------------------------+
4 rows in set (0.01 sec)
Want to fetch the content.
Code:
See below.
编译C程序
Compiling command:
gcc -lmysqlcliet my.c -o query
运行结果如下:
Running result:
================================================
Name: Petter
Email: abc@gmail.com
Tel: 12345
QQ: 54321
Birthday: 2008-11-14
Note: Loves sweet very much!
================================================
================================================
Name: Marry
Email: aa@163.com
Tel: 13456
QQ: 65431
Birthday: 2008-03-05
Note: Hates Sanlu milk powder!
================================================
================================================
Name: Jack
Email: zz@163.net
Tel: 13221
QQ: 3422
Birthday: 2007-10-02
Note: Has been in Heaven because of the magic powder mentioned above!
================================================
================================================
Name: Rose
Email: rr@hotmail.com
Tel: 343232
QQ: 2321
Birthday: 2007-12-08
Note: Jack's lover. Suffering from the damn powder
================================================
C程序代码如下:
Code:
#include stdio.h>
#include mysql/mysql.h>
int main()
{
MYSQL db;/*connector*/
MYSQL_RES* result;/*result buffer*/
MYSQL_ROW row;/*one row of the result*/
int i;
if(mysql_init(&db) ==NULL)
{
fprintf(stderr,"Fail to initialize the db.\n");
return -1;
}
if(!mysql_real_connect(&db,"localhost","root",NULL,"personal",3306,NULL,0))
{
fprintf(stderr,"Fail to connect to the server");
return -1;
}
if(mysql_query(&db,"SELECT * FROM contact") != 0)
{
fprintf(stderr,"Fail to query the db for information.\n");
return -1;
}
if ((result = mysql_store_result(&db)) == NULL)
{
fprintf(stderr,"Fail to get the result.\n");
return -1;
}
while((row=mysql_fetch_row(result)) != NULL)/*fetching each row*/
{
puts("================================================");
printf("Name: %s\n",row[0]);
printf("Email: %s\n",row[1]);
printf("Tel: %s\n",row[2]);
printf("QQ: %s\n",row[3]);
printf("Birthday: %s\n",row[4]);
printf("Note: %s\n",row[5]);
puts("================================================");
}
mysql_free_result(result);
mysql_close(&db);
return 0;
}