C語言操作mysql

?

php中 mysqli, pdo 可以用 mysqlndlibmysqlclient 實現

前者 從 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

  1. Change location to the top-level directory of the source distribution.

  2. 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 the?Makefile. 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.

  3. Build the project:

    shell> make
    
  4. 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 = 3306;my_bool reconnect = 1;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 != 0 ){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 != 0 ){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 != 0 ){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 != 0 ){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 deleteif( 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=0; i<cols; i++){printf("%s\t", my_field[i].name);}printf("\n");for(i=0; i<cols; i++){//字段類型printf("%d\t", my_field[i].type);}printf("\n");//輸出執行結果while( my_row = mysql_fetch_row(my_res) ){for(i=0; 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 TransferSource Server         : localhost
Source Server Version : 50524
Source Host           : 127.0.0.1:3306
Source Database       : testTarget Server Type    : MYSQL
Target Server Version : 50524
File Encoding         : 936Date: 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 ('1', 'A', 'xx', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('2', 'B', 'jj', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('3', 'D', 'k', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('4', 'C', 'm', 'TEMPALTE 1', '119.10');
INSERT INTO test VALUES ('5', 'B', 'y', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('6', 'D', 'k', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('7', 'C', 'm', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('8', 'E', 'n', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('9', 'D', 'z', 'TEMPALTE 3', '119.10');
INSERT INTO test VALUES ('10', 'E', 'n', 'TEMPALTE 3', '119.10');
INSERT INTO test VALUES ('11', 'A', 'x', 'TEMPALTE 2', '119.10');
INSERT INTO test VALUES ('12', 'A', 'x', 'TEMPALTE 3', '119.10');
INSERT INTO test VALUES ('13', 'A', 'x', 'TEMPALTE 4', '119.10');
INSERT INTO test VALUES ('14', 'E', 'p', 'TEMPALTE 4', '119.10');
INSERT INTO test VALUES ('15', 'A', 'x', 'TEMPALTE 5', '119.10');
INSERT INTO test VALUES ('16', 'C', 'q', 'TEMPALTE 5', '119.10');
INSERT INTO test VALUES ('17', '', '', '', '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

轉載于:https://www.cnblogs.com/siqi/p/4810369.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/375531.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/375531.shtml
英文地址,請注明出處:http://en.pswp.cn/news/375531.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Hadoop DistributedCache分布式緩存的使用

轉載請注明&#xff1a;http://www.cnblogs.com/demievil/p/4059141.html 我的github博客&#xff1a;http://demievil.github.io/ 做項目的時候遇到一個問題&#xff0c;在Mapper和Reducer方法中處理目標數據時&#xff0c;先要去檢索和匹配一個已存在的標簽庫&#xff0c;再對…

每日溫度

根據每日 氣溫 列表&#xff0c;請重新生成一個列表&#xff0c;對應位置的輸出是需要再等待多久溫度才會升高超過該日的天數。如果之后都不會升高&#xff0c;請在該位置用 0 來代替。 例如&#xff0c;給定一個列表 temperatures [73, 74, 75, 71, 69, 72, 76, 73]&#xf…

什么是Modbus

什么是Modbus 1. Modbus如何工作 Modbus是通過設備之間的幾根連線來傳遞數據&#xff0c;最簡單的設置就是主站和從站之間用一跟串口線相連。數據通過一串0或者1來傳遞&#xff0c;也就是位。0為正電壓&#xff0c;1為負電壓。位數據傳遞速度非常快&#xff0c;常見的傳輸速度為…

博客剛剛開通!

今天老賊開播了&#xff01;以后請大家多多關照&#xff01; 轉載于:https://www.cnblogs.com/xiaosayi/p/4065313.html

Android實例-拍攝和分享照片、分享文本(XE8+小米2)

結果&#xff1a; 1.分享文本不好使&#xff0c;原因不明。有大神了解的&#xff0c;請M我&#xff0c;在此十分感謝。 2.如果想支持圖片編輯&#xff0c;將Action事件的Editable改為True。 相關資料&#xff1a; 官網地址&#xff1a;http://docwiki.embarcadero.com/RADStudi…

go語言 expected ; found a

錯誤代碼&#xff0c;這是一段測試go語言類型轉換的代碼 package type_testimport "testing"type MyInt int64func TestImplicit(t *testing.T) {var a int32 1var b int64 3b (int64)avar c MyInt 4// c bt.Log(a, b, c) }報錯代碼 b (int64)a改正 b int6…

win8 metro 調用攝像頭拍攝照片并將照片保存在對應的位置

剛剛做過這類開發&#xff0c;所以就先獻丑了&#xff0c;當然所貼上的源代碼都是經過驗證過的&#xff0c;已經執行成功了&#xff0c;希望能夠給大家一些借鑒&#xff1a; 以下是metro UI代碼&#xff1a; <Pagex:Class"Camera.MainPage"xmlns"http://sche…

poj 3678 Katu Puzzle(2-sat)

Description Katu Puzzle is presented as a directed graph G(V, E) with each edge e(a, b) labeled by a boolean operator op (one of AND, OR, XOR) and an integer c (0 ≤ c ≤ 1). One Katu is solvable if one can find each vertex Vi a value Xi (0 ≤ Xi ≤ 1) suc…

go 語言 first argument to append must be slice

錯誤代碼 func TestSliceGrowing(t *testing.T) {s : [4]int{1, 2, 3, 4}for i :0; i<10; i {s append(s, i)t.Log(len(s), cap(s))} }報錯代碼 s append(s, i)原因&#xff1a;append的第一個參數必須是切片 更正 func TestSliceGrowing(t *testing.T) {s : []int{1,…

豆瓣網靜態頁面

divcss網站登錄注冊豆瓣讀書視頻 音樂同城小組閱讀 豆瓣FM東西更多豆瓣視頻 影訊&購票電視劇排行榜 分類影評預告片 向后向前3/5正在熱映全部正在熱映>>即將上映 烈日灼心 4.7終結者&#xff1a;創世紀... 4.7百團大戰 4.7刺客&#xff1a;聶隱娘 4.7近期熱門更多影視…

C++并發編程實戰(豆瓣評分5.4)

評分已說明一切&#xff0c;切勿踩坑&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01; 推薦的翻譯 C并發編程實戰 關注公眾號回復【C并發編程實…

Please use boost/bind/bind.hpp + using namespace boost::placeholders

The practice of declaring the Bind placeholders (_1, _2, …) in the global namespace is deprecated. Please use <boost/bind/bind.hpp> using namespace boost::placeholders, or define BOOST_BIND_GLOBAL_PLACEHOLDERS to retain the current behavior. 提示w…

奔跑吧,兄弟

10月底的時候&#xff0c;不能忍受老婆的奚落&#xff0c;開始了我的跑步計劃。 說說&#xff0c;跑步需要注意的事項&#xff0c;首先你得有雙跑步鞋&#xff0c;我有一次是穿了薄底鞋跑的&#xff0c;結果&#xff0c;打滿了水泡。跑步前控制飲水&#xff0c;最好在飲食后2個…

2299 Ultra-QuickSort(歸并)

合并排序第一次。連環畫看著合并看著別人的博客的想法。http://poj.org/problem?id2299 #include <stdio.h> #include <stdlib.h>#define MAX 500001int n,a[MAX], t[MAX]; long long int sum;//歸并 void Merge(int l, int m, int r) {int p0;int il, jm1;while…

由openSession、getCurrentSession和HibernateDaoSupport淺談Spring對事物的支持

由openSession、getCurrentSession和HibernateDaoSupport淺談Spring對事物的支持 Spring和Hibernate的集成的一個要點就是對事務的支持&#xff0c;openSession、getCurrentSession都是編程式事務&#xff08;手動設置事務的提交、回滾&#xff09;中重要的對象&#xff0c;Hi…

【tool】沒有需求文檔的時候如何來設計測試用例

沒有需求文檔的時候如何來設計測試用例 1.根據客戶的功能點整理測試需求追朔表&#xff1a; 一般的客戶都要把要開發軟件的功能點寫成一個表格交給市場部&#xff0c;讓市場部門轉交研發部。所以客戶的功能點是編寫測試用例一個最最重要的依據。 2.根據開發人員的Software Spec…

go返回多個值和python返回多個值對比

go package mulVals_test import "testing" func returnMultiValues(n int)(int, int){return n1, n2 }func TestReturnMultiValues(t *testing.T) {// a : returnMultiValues(5)// 這里嘗試用一個值接受多個返回值&#xff0c;將編譯錯誤a, _ : returnMultiValues(…

努力學習 HTML5 (3)—— 改造傳統的 HTML 頁面

要了解和熟悉 HTML5 中的新的語義元素&#xff0c;最好的方式就是拿一經典的 HTML 文檔作例子&#xff0c;然后把 HTML5 的一些新鮮營養充實進入。如下就是我們要改造的頁面&#xff0c;該頁面很簡單&#xff0c;只包含一篇文章。 ApocalypsePage_Original.html&#xff0c;這是…

判斷系統是大端還是小段

大端&#xff1a;高位內存存儲低序字節小端&#xff1a;高位內存存儲高序字節short a 0x0102&#xff0c;其中 01 高序字節&#xff0c; 02 低序字節 #include<stdio.h>int main() {union {short s;char c[sizeof(short)];} un;un.s 0x0102;if (sizeof(short) 2) {if…

手機頁面head中的meta元素

<meta http-equiv"Pragma" content"no-cache"> <meta http-equiv"expires" content"0"> <meta http-equiv"cache-control" content"no-cache"> 清除瀏覽器中的緩存&#xff0c;它和其它幾句合起…