设为首页 加入收藏

TOP

Linux下C语言笔记操作MySQL
2014-11-24 07:34:51 来源: 作者: 【 】 浏览:0
Tags:Linux 语言 笔记 操作 MySQL

Linux下C语言学习笔记—操作MySQL


注:下面的所有例子在mandriva linux下测试通过


1,使用c语言操作mysql之前,先在mysql里头创建一个数据库,一个表,在表里头添加数据如下:


创建数据库,库名为cusemysql:
mysql>create database cusemysql;
创建表,表名为:
mysql>use cusemysql;
mysql>create table children(childno int not null unique,fname varchar(20),age int);
添加一点数据哦:
mysql>insert into children values(5,"anny",10);
对拉,为了方便起见,把表的大致样子给大家看看



childno fname age
1 小星 9
2 大量 15


//////////////////
/* select1.c */


#include
#include
#include
#include "/usr/include/mysql/mysql.h"

int main(int argc, char *argv[])
{
MYSQL my_connection;
MYSQL_RES *res_ptr; /*指向检索的结果存放地址的指针*/
MYSQL_ROW sqlrow; /*返回的记录信息*/
MYSQL_FIELD *fd; /*字段结构指针*/
char aszflds[25][25]; /*用来存放各字段名*/
int res; /*执行查询操作后的返回标志*/
int i,j,k;


mysql_init(&my_connection);


/*mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)*/
if (mysql_real_connect(&my_connection, "127.0.0.1", "root", "你的密码","cusemysql",0,NULL,CLIENT_FOUND_ROWS))
{
printf("Connection success\n");
res = mysql_query(&my_connection, "select childno,fname,age from children where age<20");


if (res)
{
printf("SELECT error:%s\n",mysql_error(&my_connection));
}
else
{
res_ptr=mysql_store_result(&my_connection);
if(res_ptr)
{
printf("Retrieved %lu Rows\n",(unsigned long)mysql_num_rows(res_ptr));
/*取得各字段名*/
for(i=0;fd=mysql_fetch_field(res_ptr);i++)
strcpy(aszflds[i],fd->name);
/*输出各条记录*/
printf("下面是检索出的各条记录信息:\n");
j=mysql_num_fields(res_ptr);
for(i=0;i printf("%s\t",aszflds[i]);
printf("\n");
while((sqlrow=mysql_fetch_row(res_ptr)))
{
for(i=0;i printf("%s\t",sqlrow[i]);
printf("\n");
}
if (mysql_errno(&my_connection))
{
fprintf(stderr,"Retrive error:s\n",mysql_error(&my_connection));
}
}
mysql_free_result(res_ptr);
}
mysql_close(&my_connection);
}


else
{
fprintf(stderr, "Connection failed\n");


if (mysql_errno(&my_connection))
{
fprintf(stderr, "Connection error %d: %s\n",
mysql_errno(&my_connection),
mysql_error(&my_connection));
}
}
return EXIT_SUCCESS;
}
//////////////////////////////////////
主要要注意的几个地方是:
1,mysql.h的路径,必须确定它的绝对路径哦(这句话是错误的,只要在编译是把对应库编译进去即可,具体操作方法请查询本博客)
2,注意你的数据库的用户名和密码是否正确
3,在编译的时候必须包含这个库文件mysqlclient.a[记不太清楚,不过你可以直接包含它所在的目录下的所有库,肯定就没有问题,


各方意见:
一.
编译方法有点不规范。


正确的应该是这样:


1.在程序开头包含头文件应这样写:
#include (这里要找出mysql.h的文件路径,方法是 $find / -name -a


我的路径是 "/usr/include/mysql“所以这里很重要


2.编译应这样写:(原文)


$ gcc -o mysql mysql.c `mysql_config --cflags --libs`(我测试了,不可用,估计大的思想是对的)


我用的命令


$gcc -o select $(mysql_config --cflags) select.c $(mysql_config --libs)


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux 两种方式创建内核线程 下一篇Linux 自动生成设备节点

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis 分布式锁全解 (2025-12-25 17:19:51)
·SpringBoot 整合 Red (2025-12-25 17:19:48)
·MongoDB 索引 - 菜鸟 (2025-12-25 17:19:45)
·What Is Linux (2025-12-25 16:57:17)
·Linux小白必备:超全 (2025-12-25 16:57:14)