您的位置:首页 > 运维架构 > Linux

Linux下C语言Mysql数据库使用范例

2016-04-28 12:26 477 查看
数据库:
CREATE DATABASE test;
CREATE TABLE `test` (

`id` int(11) NOT NULL auto_increment,

PRIMARY KEY (`id`)

);

ALTER TABLE `test`

ADD COLUMN `name` varchar(20);

代码:

1 /*
2  ============================================================================
3  Name        : mysql_test.c
4  Author      :
5  Version     :
6  Copyright   : Your copyright notice
7  Description : Hello World in C, Ansi-style
8  ============================================================================
9  */
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14
15 #include <mysql/mysql.h>
16
17 MYSQL *g_conn; // mysql 连接
18  MYSQL_RES *g_res; // mysql 记录集
19  MYSQL_ROW g_row; // 字符串数组,mysql 记录行
20
21 #define MAX_BUF_SIZE 1024 // 缓冲区最大字节数
22
23 const char *g_host_name = "localhost";
24 const char *g_user_name = "root";
25 const char *g_password = "root";
26 const char *g_db_name = "test";
27 const unsigned int g_db_port = 3306;
28
29 void print_mysql_error(const char *msg) { // 打印最后一次错误
30     if (msg)
31         printf("%s: %s\n", msg, mysql_error(g_conn));
32     else
33         puts(mysql_error(g_conn));
34 }
35
36 int executesql(const char * sql) {
37     /*query the database according the sql*/
38     if (mysql_real_query(g_conn, sql, strlen(sql))) // 如果失败
39         return -1; // 表示失败
40
41     return 0; // 成功执行
42 }
43
44
45 int init_mysql() { // 初始化连接
46     // init the database connection
47     g_conn = mysql_init(NULL);
48
49     /* connect the database */
50     if(!mysql_real_connect(g_conn, g_host_name, g_user_name, g_password, g_db_name, g_db_port, NULL, 0)) // 如果失败
51         return -1;
52
53     // 是否连接已经可用
54     if (executesql("set names utf8")) // 如果失败
55         return -1;
56
57     return 0; // 返回成功
58 }
59
60
61 int main(void) {
62     puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
63
64     if (init_mysql());
65         print_mysql_error(NULL);
66
67     char sql[MAX_BUF_SIZE];
68     sprintf(sql, "INSERT INTO `test`(`name`) VALUES('testname')");
69
70     if (executesql(sql))
71         print_mysql_error(NULL);
72
73     if (executesql("SELECT * FROM `test`")) // 句末没有分号
74         print_mysql_error(NULL);
75
76     g_res = mysql_store_result(g_conn); // 从服务器传送结果集至本地,mysql_use_result直接使用服务器上的记录集
77
78     int iNum_rows = mysql_num_rows(g_res); // 得到记录的行数
79     int iNum_fields = mysql_num_fields(g_res); // 得到记录的列数
80
81     printf("共%d个记录,每个记录%d字段\n", iNum_rows, iNum_fields);
82
83     puts("id\tname\n");
84
85     while ((g_row=mysql_fetch_row(g_res))) // 打印结果集
86         printf("%s\t%s\n", g_row[0], g_row[1]); // 第一,第二字段
87
88     mysql_free_result(g_res); // 释放结果集
89
90     mysql_close(g_conn); // 关闭链接
91
92     return EXIT_SUCCESS;
93 }


编译命令:gcc mysqltest.c -lmysqlclient

运行结果:

1 !!!Hello World!!!
2
3 共1个记录,每个记录2字段
4 id    name
5
6 2    testname


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: