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

来源:互联网 发布:高级java工程师充电班 编辑:程序博客网 时间:2024/04/30 01:47
今天上数据库的时候刚上到嵌入式sql,感觉非常有意思,上课的时候就想反正做搜索引擎要用到c连接mysql数据库的,到底是怎么实现?想入非非,呵呵.

下来的时候赶紧找资料,刚才搜索了几下,终于找到一些:
1,[比较详细]在 C 里嵌入 SQL:http://www.pgsqldb.org/pgsqldoc-7.4/ecpg.html
2,[在MySQL数据库中使用C执行SQL语句]:http://www.dvbbs.net/tech/data/2006031818989.asp
3,MySQL客户工具和API:http://www.yesky.com/imagesnew/software/mysql/manual_Clients.html
4,基于mysql的高性能数据库应用开发:http://cache.baidu.com/c?word=mysql%3B%5F%3Breal%3B%5F%3Bconnect%2C%B2%CE%CA%FD&url=http%3A//www%2Edaima%2Ecom%2Ecn/Info/76/Info27780/&b=0&a=2&user=baidu


大家一起来开始练习罗
注:下面的所有例子在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,"花儿",10);
对拉,为了方便起见,把表的大致样子给大家看看


childno         fname       age
1                小星      9
2                大量      15



2 ,下面进行具体的操作

插入:insert    

好的,我们现编辑一段c代码,取名为insert.c

///////////////////////////////////
/*  insert.c */
#include <stdio.h>
#include <stdlib.h>
#include "/usr/local/mysql/include/mysql/mysql.h" 
/*注意哦,上面必须是mysql.h的绝对地址,一般在mysql下的include目录下,仔细看看你的在哪里?*/

int main(int argc, char *argv[])
{
MYSQL my_connection;

int res;

mysql_init(&my_connection);

/*mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)*/
if (mysql_real_connect(&my_connection, "localhost", "root", "","cusemysql",0,NULL,CLIENT_FOUND_ROWS))
{
    printf("Connection success/n");
    res = mysql_query(&my_connection, "insert into children values(10,'Ann',5)");

    if (!res)
    {
        printf("Inserted %lu rows/n",(unsigned long)mysql_affected_rows(&my_connection));
/*里头的函数返回受表中影响的行数*/
    }
    else
    {
    //分别打印出错误代码及详细信息
        fprintf(stderr, "Insert error %d: %s/n",mysql_errno(&my_connection),mysql_error(&my_connection));
    }
    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;
}
/////////////////////////////////////////////
代码写完了,要编译哦
#gcc -o insert insert.c -L /usr/local/mysql/lib/mysql/*.a -lz
ok,现在我们执行看看
#./insert
Connection Success
Inserted 1 rows