文档详情

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

发布:2017-06-26约5.14万字共36页下载文档
文本预览下载声明
Linux C Mysql Linux C Mysql LLiinnuuxx下CC语言MMyyssqqll数据库使用范例 数据库: CREATEDATABASE test; CREATETABLE `test`( `id` int(11) NOT NULLauto_increment, PRIMARY KEY (`id`) ); ALTERTABLE `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#includestdio.h 12#includestdlib.h 13#includestring.h 14 15#includemysql/mysql.h 16 17MYSQL*g_conn;// mysql 连接 18 MYSQL_RES*g_res;// mysql 记录集 19 MYSQL_ROW g_row;// 字符串数组,mysql 记录行 20 21#define MAX_BUF_SIZE 1024// 缓冲区最大字节数 22 23const char *g_host_name= localhost; 24const char *g_user_name= root; 25const char *g_password= root; 26const char *g_db_name= test; 27const unsignedint g_db_port= 3306; 28 29void 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 36int 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 45int 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 61int 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 pri
显示全部
相似文档