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=Debug
By default, the installation location for Connector/C is
/usr/local/mysql
. To change this location, use theCMAKE_INSTALL_PREFIX
option to specify a different directory when generating theMakefile
. For example:shell>
cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=/opt/local/mysql
For other CMake options that you might find useful, see Other Connector/C Build Options.
Build the project:
shell>
make
As
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 ...
随机推荐
- Android开发--FrameLayout的应用
1.简介 frameLayout为框架布局,该布局的特点为层层覆盖,即最先放置的部件位于最下层,最后放置的部件位于最上层. 2.构建 如图所示,该视图中有五个TextView.其中,tv1放置在最底层 ...
- State(状态)
props和state.props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变. 对于需要改变的数据,我们需要使用state.般来说,你需要在constructor中初始化st ...
- 通过ksoap2-android来调用Web Service操作的实例
import java.io.IOException; import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObjec ...
- DeepLearning之路(一)逻辑回归
逻辑回归 1. 总述 逻辑回归来源于回归分析,用来解决分类问题,即预测值变为较少数量的离散值. 2. 基本概念 回归分析(Regression Analysis):存在一堆观测资料,希望获得数据内 ...
- candence 知识积累4
一.PCB布局约束: 1.尺寸规划:PCB大小要合适,PCB太大印制线路长,阻抗增加.太小散热不好,易受干扰. 2.PCB尺寸确定后要确定特殊器件的位置. 3.尽可能缩短高频元器件之间的连线,设法减少 ...
- 集合ArrayList
/*集合ArrayList * 例如: * 1.创建:ArrayList<Egg> myList = new ArrayList<Egg>(); * Egg类型的集合 ...
- js导入导出excel
导入: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Unti ...
- Classes
Class Organization Following the standard Java convention, a class should begin with a list of varia ...
- [转]http://lua-users.org/wiki/LpegTutorial
Simple Matching LPeg is a powerful notation for matching text data, which is more capable than Lua s ...
- C# 多线程同步和线程通信
多线程通信 1. 当线程之间有先后的依赖关系时,属于线程之间的通信问题.也就是后一个线程要等待别的一个或多个线程全部完成,才能开始下一步的工作.可以使用: WaitHandle Class WaitH ...