C语言操作mysql
php中 mysqli, pdo 可以用 mysqlnd 或 libmysqlclient 实现
前者 从 php 5.3.0起已内置到php中, 并且支持更多的特性,推荐用 mysqlnd
mysqlnd , libmysqlclient 对比:
http://php.net/manual/en/mysqlinfo.library.choosing.php
mysqlnd 目前是php源码的一部分
http://php.net/manual/en/intro.mysqlnd.php
php编译参数:
// Recommended, compiles with mysqlnd
$ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql=mysqlnd // Alternatively recommended, compiles with mysqlnd as of PHP 5.4
$ ./configure --with-mysqli --with-pdo-mysql --with-mysql // Not recommended, compiles with libmysqlclient
$ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config --with-mysql=/path/to/mysql_config
环境准备:
1、安装 libmysqlclient
http://cdn.mysql.com/Downloads/Connector-C/mysql-connector-c-6.0.2.tar.gz
Change location to the top-level directory of the source distribution.
Generate the
Makefile:shell>
cmake -G "Unix Makefiles"Or, for a Debug build:
shell>
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=DebugBy default, the installation location for Connector/C is
/usr/local/mysql. To change this location, use theCMAKE_INSTALL_PREFIXoption to specify a different directory when generating theMakefile. For example:shell>
cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=/opt/local/mysqlFor other CMake options that you might find useful, see Other Connector/C Build Options.
Build the project:
shell>
makeAs
root, install the Connector/C headers, libraries, and utilities:root-shell>
make install
示例代码:
//main.c
//gcc main.c -o test -lmysqlclient // @link http://dev.mysql.com/doc/refman/5.6/en/c-api-function-overview.htm // libmysqlclient library #include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h> MYSQL *get_conn()
{
//连接配置
char *host = "127.0.0.1";
char *user = "root";
char *passwd = "";
char *db = "test";
int port = ;
my_bool reconnect = ; MYSQL *my_con = (MYSQL *)malloc( sizeof(MYSQL) ); //数据库连接句柄 //连接数据库
mysql_init(my_con); mysql_options(my_con, MYSQL_OPT_RECONNECT, &reconnect);
mysql_real_connect(my_con, host, user, passwd, db, port, NULL, CLIENT_FOUND_ROWS); mysql_query(my_con, "set names utf8"); return my_con;
} /**
* 释放空间,关闭连接
*
* @param mysql
* @return
*/
void free_conn(MYSQL *mysql)
{
mysql_close(mysql);
free(mysql);
} //发生错误时,输出错误信息,关闭连接,退出程序
void error_quit(const char *str, MYSQL *connection)
{
fprintf(stderr, "%s\n errno: %d\n error:%s\n sqlstat:%s\n",
str, mysql_errno(connection),
mysql_error(connection),
mysql_sqlstate(connection)); if( connection != NULL )
{
mysql_close(connection);
} free(connection); exit(EXIT_FAILURE);
} void insert(MYSQL *my_con)
{
int res; res = mysql_query(my_con, "INSERT INTO test(fid) VALUES(null)");
if( res != )
{
error_quit("Select fail", my_con);
} printf("affected rows:%d \n", mysql_affected_rows(my_con));
printf("last insertId :%d \n", mysql_insert_id(my_con)); } void update(MYSQL *my_con)
{
int res; res = mysql_query(my_con, "UPDATE test SET FScore=119.10");
if( res != )
{
error_quit("Select fail", my_con);
} printf("affected rows:%d \n", mysql_affected_rows(my_con)); } void delete(MYSQL *my_con)
{
int res; res = mysql_query(my_con, "DELETE FROM test WHERE FID=31");
if( res != )
{
error_quit("Select fail", my_con);
} printf("affected rows:%d \n", mysql_affected_rows(my_con)); } void query(MYSQL *my_con)
{
MYSQL_RES *my_res; //查询结果
MYSQL_FIELD *my_field; //结果中字段信息
MYSQL_ROW my_row; //结果中数据信息 unsigned long *lengths;
int cols, res, i; //获取整个表的内容 res = mysql_query(my_con, "SELECT * FROM test LIMIT 5");
if( res != )
{
error_quit("Select fail", my_con);
} /*
mysql_query , mysql_real_query 区别 While a connection is active, the client may send SQL statements to the server using mysql_query() or mysql_real_query().
The difference between the two is that mysql_query() expects the query to be specified as a null-terminated string whereas mysql_real_query() expects a counted string.
If the string contains binary data (which may include null bytes), you must use mysql_real_query(). */ //从服务端取回结果 mysql_store_result 会把数据全部拉取到客户端, mysql_use_result() 则不会
my_res = mysql_store_result(my_con); // A MYSQL_RES result structure with the results. NULL (0) if an error occurred or has not result like delete
if( NULL == my_res ) //可以通过返回值来判断是否是 select
{
error_quit("Get result fail", my_con);
} // mysql_row_seek(), mysql_data_seek() , mysql_num_rows 只有在用mysql_store_result 才可以使用
printf("num rows:%d \n", mysql_num_rows(my_res)); //获取表的列数
cols = mysql_num_fields(my_res);
printf("num cols:%d \n", cols); //获取字段信息
my_field = mysql_fetch_fields(my_res); for(i=; i<cols; i++)
{
printf("%s\t", my_field[i].name);
}
printf("\n"); for(i=; i<cols; i++)
{
//字段类型
printf("%d\t", my_field[i].type);
} printf("\n"); //输出执行结果
while( my_row = mysql_fetch_row(my_res) )
{
for(i=; i<cols; i++)
{
//数据长度
lengths = mysql_fetch_lengths(my_res);
printf("%s(%lu)\t", my_row[i], lengths[i]);
} printf("\n");
} mysql_free_result(my_res); } void status(MYSQL *my_con)
{
printf("mysql_get_server_info: %s \n", mysql_get_server_info(my_con));
printf("mysql_stat: %s \n", mysql_stat(my_con));
printf("mysql_get_proto_info: %u \n", mysql_get_proto_info(my_con)); } int main(int argc, char *argv[])
{
//连接数据库
MYSQL *my_con = get_conn();
if( NULL == my_con )
{
error_quit("Connection fail", my_con);
} printf("Connection success \n"); status(my_con); insert(my_con); delete(my_con); update(my_con); //select
query(my_con); // free the memory
free_conn(my_con); return EXIT_SUCCESS;
}
test.sql
/*
Navicat MySQL Data Transfer Source Server : localhost
Source Server Version : 50524
Source Host : 127.0.0.1:3306
Source Database : test Target Server Type : MYSQL
Target Server Version : 50524
File Encoding : 936 Date: 2015-09-16 15:02:57
*/ create DATABASE test; SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `test`
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`FID` int(11) NOT NULL AUTO_INCREMENT,
`FTableName` char(60) NOT NULL DEFAULT '',
`FFieldName` char(30) NOT NULL DEFAULT '',
`FTemplate` char(30) NOT NULL DEFAULT '',
`FScore` decimal(5,2) NOT NULL DEFAULT '0.00' COMMENT 'ио╩§',
PRIMARY KEY (`FID`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=latin1; -- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO test VALUES ('', 'A', 'xx', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('', 'B', 'jj', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('', 'D', 'k', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('', 'C', 'm', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('', 'B', 'y', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('', 'D', 'k', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('', 'C', 'm', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('', 'E', 'n', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('', 'D', 'z', 'TEMPALTE 3', '119.10');
INSERT INTO test VALUES ('', 'E', 'n', 'TEMPALTE 3', '119.10');
INSERT INTO test VALUES ('', 'A', 'x', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('', 'A', 'x', 'TEMPALTE 3', '119.10');
INSERT INTO test VALUES ('', 'A', 'x', 'TEMPALTE 4', '119.10');
INSERT INTO test VALUES ('', 'E', 'p', 'TEMPALTE 4', '119.10');
INSERT INTO test VALUES ('', 'A', 'x', 'TEMPALTE 5', '119.10');
INSERT INTO test VALUES ('', 'C', 'q', 'TEMPALTE 5', '119.10');
INSERT INTO test VALUES ('', '', '', '', '119.10');

参考文档:http://dev.mysql.com/doc/refman/5.6/en/c-api-function-overview.html
http://www.linuxfocus.org/ChineseGB/September2003/article304.shtml#304lfindex3
C语言操作mysql的更多相关文章
- Linux C语言操作MySQL
原文:Linux C语言操作MySQL 1.MySQL数据库简介 MySQL是一个开源码的小型关系数据库管理系统,体积小,速度快,总体成本低,开源.MySQL有以下特性: (1) 使用C和C++编写, ...
- Go语言操作MySQL数据库
Go语言操作MySQL数据库 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用 ...
- 使用Go语言操作MySQL数据库的思路与步骤
最近在做注册登录服务时,学习用Go语言操作MySQL数据库实现用户数据的增删改查,现将个人学习心得总结如下,另外附有代码仓库地址,欢迎各位有兴趣的fork. 软件环境:Goland.Navicat f ...
- c语言操作mysql数据库
c语言操作Mysql数据库,主要就是为了实现对数据库的增.删.改.查等操作,操作之前,得先连接数据库啊,而连接数据库主要有两种方法.一.使用mysql本身提供的API,在mysql的安装目录中可可以看 ...
- GO学习-(23) Go语言操作MySQL + 强大的sqlx
Go语言操作MySQL MySQL是业界常用的关系型数据库,本文介绍了Go语言如何操作MySQL数据库. Go操作MySQL 连接 Go语言中的database/sql包提供了保证SQL或类SQL数据 ...
- go语言操作mysql范例(增删查改)
http://blog.csdn.net/jesseyoung/article/details/40398321 go语言连接mysql简介 go官方仅提供了database package,d ...
- 用C语言操作MySQL数据库,进行连接、插入、修改、删除等操作
C/C++ code ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 3 ...
- Go语言操作MySQL
MySQL是常用的关系型数据库,本文介绍了Go语言如何操作MySQL数据库. Go操作MySQL 连接 Go语言中的database/sql包提供了保证SQL或类SQL数据库的泛用接口,并不提供具体的 ...
- golang学习之旅:使用go语言操作mysql数据库
1.下载并导入数据库驱动包 官方不提供实现,先下载第三方的实现,点击这里查看各种各样的实现版本.这里选择了Go-MySQL-Driver这个实现.地址是:https://github.com/go-s ...
随机推荐
- oracle with as
http://blog.csdn.net/a9529lty/article/details/4923957/
- Visual Studio 拓展插件——Image Optimizer
一句话概括效用:在Visual Studio的解决方案中,为图片或包含图片的文件夹添加右键菜单,可对图片进行压缩,无损压缩. 在VS扩展工具中安装 安装好后在VS资源管理器中选择图片右键,在右键菜单中 ...
- 反向Ajax,实现服务器向客户端推送消息
反向Ajax的基本概念是客户端不必从服务器获取信息,服务器会把相关信息直接推送到客户端.这样做的目的是解决Ajax传统Web模型所带来的一个限制:实时信息很难从技术上解决.原因是,客户端必须联系服务器 ...
- 用CSS定义每段首行缩进2个字符 转
应该遵循w3c所制定的html/xhtml标准来使用tag和编写网页.如果你对此不太了解,可以到w3c的网站www.w3.org去找相关资料,或者买一本xhtml的书(注意不要买过时的html的书,尽 ...
- JS的(function($){})(query)
function(arg){...} 这就定义了一个匿名函数,参数为arg 而调用函数时,是在函数后面写上括号和实参的,由于操作符的优先级,函数本身也需要用括号,即:(function(arg){.. ...
- UIkit框架之uUInavigationController
1.继承链:UIviewcontroller:uiresponder:NSObject 2.如果你想使用一些动画转换,可以遵守 UINavigationControllerDelegate 3.创建导 ...
- BZOJ 1015 并查集+离线倒序
统计块个数写错了调了好久啊,BZOJ1696的弱化版本. #include <iostream> #include <cstring> #include <algorit ...
- iOS 利用 Framework 进行动态更新
http://nixwang.com/2015/11/09/ios-dynamic-update/ 前言 目前 iOS 上的动态更新方案主要有以下 4 种: HTML 5 lua(wax)hotpat ...
- HDU 4777 Rabbit Kingdom (2013杭州赛区1008题,预处理,树状数组)
Rabbit Kingdom Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)To ...
- asp.net与asp.net 优缺点
Asp.net Mvc架构模式是一种 低耦合.可测试的web应用程序框架,它是基于CLR和成熟的MVC架构构建的.ASP.NET MVC不支持ViewState和服务器控件. Asp.net优点: 1 ...