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 ...
随机推荐
- 八款你不得不知的开源前端JS框架
angular.js Angular.JS是一个开源的JavaScript框架,最适于开发客户端的单页面应用.它实现了前端MVC架构,专注于扩展HTML功能,提供动态数据绑定(Data Binding ...
- web项目的日志打印位置设置
1, 若在项目中放logback.groovy文件(如: src/test/resource下),则日志会打印到控制台上. logback.groovy 内容如下: // // Built on Fr ...
- wp8.1 Study16:网络之 使用Azure移动服务及利用Azure推送通知服务
一.WP8.1有关网络的API WP8.1与其它平台的对比如下图: 二.Azure移动服务 前提: Azure移动服务可以让使用者的数据存放在云空间,从而方便使用者的App在不同平台上的数据共享. 1 ...
- C语言基础--循环 递归打印乘法表
for循环打印乘法表: #include <stdio.h> // for循环打印乘法表 int main(int argc, const char * argv[]) { //矩形 ; ...
- 初学JavaScript七大注意事项
知识说明: 初学JavaScript,注意以下七大细节,在实现同样功能的情况下,让我们的代码更易懂.效率更高. 一.简化代码 例如:创建对象 之前是这样的: Var car = new object( ...
- Android Studio 1.5错误
Error:Unable to start the daemon process: could not reserve enough space for object heap. Please ass ...
- 2014年4月份第1周51Aspx源码发布详情
基于Extjs4+MVC4权限管理源码 2014-3-31 [VS2012]源码描述: 20140331更新:修改部门管理中bug 20140303更新:增加部门管理模块,主要包含部门添加,编辑,删 ...
- 带卡扣的网卡接口使用小Tips,大家注意插拔网线的手法啊!
最近入手了一台X401,因为机器本身比较薄,它的网卡接口是有卡扣的,插网线的时候卡扣往下沉,这种设计应该有很多机型都采用了.但是大家有没有发现啊,这种接口的卡扣,时间长了,可能会有点松动.为了保护爱机 ...
- SqlServer性能优化(一)
一:数据存储的方式: 1.数据文件:.mdf或.ndf 2.日志文件:.ldf 二:事务日志的工作步骤: 1.数据修改由应用程序发出(在缓冲区进行缓存) 2.数据页位于缓存区缓冲中,或者读入缓冲区缓存 ...
- 监听调试web service的好工具TCPMon
监听调试web service的好工具TCPMonhttp://ws.apache.org/commons/tcpmon/download.cgi TCPMon Tutorial Content In ...