一.引用博客一些用法介紹:html
Libzdb挺強大, 支持MySQL Oracle SQLite PostgreSQL,支持C和C++ Object C,不能在Window下用(看源碼是由於基於Linux線程機制編寫實現)。mysql
遺憾的是找個資料太費勁,只能到Libzdb官網:點此進入 ,今正看着上面英文文檔,忽然網站就登不進去了,才發現國內論壇其實搜不出什麼資料。ios
本文主要介紹Libzdb函數使用,幫理解英文文檔有困難的朋友作下翻譯。sql
庫結構以下 :數據庫
首先下載libzdb的源碼安裝包,解壓,在目錄下執行./configure make make install 安裝。。以我本身爲例,裝完後再/usr/local/lib下有對應庫文件。api
1 數組
線程池根據URL對象建立,URL對象經過char* 形式的URL生成,url中已經包含數據庫類型,數據庫名 用戶密碼等參數。形如:oracle
database://[user:password@][host][:port]/database[?propertyName1][=propertyValue1]app
MYSQL訪問:less
mysql://localhost:3306/test?user=root&password=swordfish
mysql://root:swordfish@localhost:3306/test
ORACLE訪問:
oracle://localhost:1521/test?user=scott&password=tiger
oracle:///servicename?user=scott&password=tiger
SQLITE訪問:
sqlite:///var/sqlite/test.db?synchronous=normal&heap_limit=8000&foreign_keys=on
PostgreSQL訪問:
postgresql://root:swordfish@localhost/test?use-ssl=true
postgresql://localhost:5432/test?user=root&password=swordfish
二、
開啓鏈接池
ConnectionPool_new(URL_T url) 根據URL生成鏈接池對象ConnectionPool_T,
ConnectionPool_start(ConnectionPool_T t); 開啓數據庫鏈接池(默認鏈接池大小爲5),若是想自定義,需在開啓前使用ConnectionPool_setInitialConnections函數設置。用法以下:
從數據庫池中獲取一個鏈接(此時活動鏈接+1):Connection_T ConnectionPool_getConnection (T P);
使用完畢後將鏈接放回鏈接池(此時活動鏈接-1):void Connection_close (Connection_T C)
或者voidConnectionPool_returnConnection (T P, Connection_T connection)
三、
獲取鏈接以後,執行數據庫SQL語句:
(具體看官網介紹)
此處T 表明 Connection_T , Connection_execute 用於執行數據庫插入、更新、刪除等操做。Connection_executeQuery用於數據庫查詢,返回結果集。
四、
遊標移動至結果集下一行intResultSet_next (ResultSet_T R), 結果無下一行則返回false ,不然返回true。關於結果集其餘操做函數以下 :
代碼實例:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<zdb/zdb.h> #include<zdb/Exception.h> #include<zdb/Connection.h> #include<zdb/URL.h> /* * 做者:擱淺的貝 * 編譯方式:gcc main.c -I /usr/local/include/zdb/ -o main -lzdb * */ int main(int agc,char** argv) { URL_T url = URL_new("mysql://localhost/AllinpayDB?user=root&password=root"); if(url==NULL) { printf("URL parse ERROR!\n"); return 0; } ConnectionPool_T pool = ConnectionPool_new(url); //設置初始化鏈接數目 ConnectionPool_setInitialConnections(pool,20); //開啓線程池 ConnectionPool_start(pool); //從線程池中取出鏈接(活動鏈接數+1) Connection_T con = ConnectionPool_getConnection(pool); //執行SQL語句,返回結果集 ResultSet_T result = Connection_executeQuery(con, "select * from AlipayTrans"); //輸出所有鏈接數目 printf("ALL NUMBE:%d\n",ConnectionPool_size(pool)); //輸出活動鏈接數目 printf("ACTIVE NUMBER:%d\n",ConnectionPool_active(pool)); while(ResultSet_next(result)) //遊標滑到下一行 { //獲取列名 ResultSet_getColumnName //獲取列值 ResultSet_getString printf("column: %s\n",ResultSet_getColumnName(result,2)); //根據列名獲取值ResultSet_getStringByName printf("%s\n ",ResultSet_getStringByName(result,"result_code")); //根據列索引獲取列值 [注意索引是從1開始不是0] printf("%s\n ",ResultSet_getString(result,3)); } //關閉鏈接(活動鏈接-1) Connection_close(con); //將鏈接池與數據庫分離 ConnectionPool_stop(pool); ConnectionPool_free(&pool); URL_free(&url); return 0; }
二.官網手冊摘錄用法實例以及簡單翻譯:
ZDB from DBS:
1.connection.h
connect_execute(): 執行返回無結果集sql 語句
Connection_executeQuery() : is used to execute a sql select statement and return a result set. 這個方法之只能handle values which can be exprssed as c_strings的sql語句。關於C_string:http://www.cprogramming.com/tutorial/lesson9.html
Connection_prepareStatement():用於執行非cstring類型的sql語句,如大對象二進制語句。 is used to obtain a PreparedStatement object。A PreparedStatement "lives" until the Connection is returned to the Connection Pool.
2. 關於結果集關閉
A ResultSet lives until the
next call to Connection execute or until the Connection is returned
to the Connection Pool. If an error occur during execution, an SQLException is thrown.
3.關於開啓事務
Any SQL statement that changes the database (basically, any SQL command other than SELECT) will automatically start a transaction if one is not already in effect. Automatically started transactions are committed at the conclusion of the command.
4.關於Connection_prepareStatement()
PreparedStatement 是以前編譯的好的用於後續執行的二進制文件。
A PreparedStatement is created by calling Connection_prepareStatement().
兩個例子:
Result Sets:
Here is another example where we use a Prepared Statement to execute a query which returns a Result Set:
PreparedStatement_T p = Connection_prepareStatement(con, "SELECT id FROM employee WHERE name LIKE ?");
PreparedStatement_setString(p, 1, "%Kaoru%");
ResultSet_T r = PreparedStatement_executeQuery(p);
while (ResultSet_next(r))
printf("employee.id = %d\n", ResultSet_getInt(r, 1));
A ResultSet returned from PreparedStatement_executeQuery() "lives" until the Prepared Statement is executed again or until the Connection is returned to the Connection Pool.
A PreparedStatement can be reused. That is, the method PreparedStatement_execute() can be called one or more times to execute the same statement. Clients can also set new in parameter values and re-execute the statement as shown in this example:
PreparedStatement_T p = Connection_prepareStatement(con, "INSERT INTO employee(name, picture) VALUES(?, ?)");
for (int i = 0; employees[i].name; i++)
{
PreparedStatement_setString(p, 1, employees[i].name);
PreparedStatement_setBlob(p, 2, employees[i].picture, employees[i].picture_size);
PreparedStatement_execute(p);
}
5.Result
A ResultSet is created by executing a SQL SELECT statement using either Connection_executeQuery() or PreparedStatement_executeQuery().
A ResultSet maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row.
能夠用循環來編譯結果集,可是這樣的話只能從頭到尾執行一次,故通常可用序號或者名字來具體獲取對應的字段值,用序號的方法,編號從1開始。
6.關於上文提到Cstring文章的簡單翻譯。
在C++中有兩種類型字符串(strings):C-style strings and C++-style strings。本文將討論C-strings.
C-style strings are really arrays,可是string類型還有一些獨有的函數,如adding to strings, finding the length of strings, and also of checking to see if strings match。
字符串的定義爲:anything that contains more than one character strung together。例如:"this".單個字符儘管通常被當作字符串使用,可是不是字符串,Strings are arrays of chars. String literals are words surrounded by double quotation marks,例如:"This is a static string"。
用char string[50],便可聲明一個長度爲50的字符串,字符使用長度爲49.由於字符串以佔一個字符的空字符結尾:'\0'.
注意:char *arry也是一個字符串,好比:arry = new char[256],which allows you to access arry just as if it were an array.刪除該字符串語法爲:delete [] arry; 這將釋放前面聲明佔用的256字節的內存。
Strings are useful for holding all types of long input.若是想輸入姓名等,能夠用你字符串類型,如用cin>>進行輸入一個字符串,可是這種輸入方式在讀到一個空格時將結束輸入。爲處理這種狀況,能夠用cin.getline函數進行輸入。Technically cin是一個類(相似於結構體),你能夠調用其中的成員函數。而最重要的即是如何去使用這些函數。
getline函數的原型爲:istream& getline(char *buffer, int length, char terminal_char);
char *buffer是一個指向字符數組第一個元素的指針(The char *buffer is a pointer to the first element of the character array, so that it can actually be used to access the array.)int length是輸入字符串的最大長度。 char terminal_char表示當用戶輸入該字符時函數退出。要注意的是,改截止字符是不會被輸入的。(Keep in mind that it will discard whatever the terminal character is.)
用一種情形是調用時沒有輸入截止字符,如cin.getline(arry,50).此時 '\n' is the way of actually telling the compiler you mean a new line,即'\n'就是截止符。
eg:
#include <iostram>
using namespace std;
int main()
{
char string[256]; //a nice long string;
cout<<"please input a long string:";
cin.getline(string, 256, '\n'); //input goes into string
cout <<"your long string was:"<<string<<endl;
cin.get();
}
Remember that you are actually passing the address of the array when you pass string because arrays do not require an address operator (&) to be used to pass their address。(當你調用函數時,當你輸入string時,其實傳遞給函數的是一個地址,由於數組是不須要取地址符 &的)
cstring是一個包含了不少對字符串操做函數的頭文件,其中字符串比較函數strcmp 即是其一:
int strcmp ( const char *s1, const char *s2 )
strcmp will accept two strings. It will return an integer. This integer will either be:
Negative if s1 is less than s2.
Zero if s1 and s2 are equal.
Positive if s1 is greater than s2。
Strcmp函數是區分大小寫的(case sensitive)。Strcmp also passes the address of the character array to the function to allow it to be accessed.(字符串也能夠傳遞字符數組地址)。
char *strcat ( char *dest, const char *src );
鏈接函數,其將第二個字符串內容加到第一個字符串後,並返回一個指向黏貼完以後的整個字符串的指針,改函數假定了有一個足夠長的空間去存取黏貼完以後的字符串。(t returns a pointer to the concatenated string. Beware this function, it assumes that dest is large enough to hold the entire contents of src as well as its own contents. )
char *strcpy ( char *dest, const char *src );
拷貝函數:which means it copies the entire contents of src into dest. The contents of dest after strcpy will be exactly the same as src such that strcmp ( dest, src ) will return 0.
size_t strlen ( const char *s );
字符串長度函數,長度值是減去'\0'的長度(strlen will return the length of a string, minus the terminating character ('\0').)。size_t是一個非負整數。
eg:
#include <iostram> //for cout
#include <cstring> //for the string function
using namespace std;
int main( )
{
char name[50];
char lastname[50];
char fullname[100]; //big enough to contain the name and lastname.
cout <<"please enter your name:";
cin.getline(name, 50);
if (strcmp(name, "julinene")==0) //equal strings
cout <<"that's my name 2."<<endl;
else
cout<<"that is not my name."<<endl;
if ((strcmp(name," ")==0)
cout <<"the name inputed is invalid"<<endl;
//find the length of the name
cout<<"your name is "<<strlen(name)<<"letters long\n";
cout <<"your last name:";
cin.getline(lastname, 50);
fullname[0] ='\0'; //strcat searches for '\0' to cat after
strcat(fullname,name); //copy name into fullname
strcat(fullname, " "); //separate the name by space
strcat(fullname,lastname);
cout<<"your fullname is"<<fullname<<endl;
cin.get();
return 0;
}
可是以上方法有必定問題,即會依賴於Null結束符。 The above string functions all rely on the existence of a null terminator at the end of a string. This isn't always a safe bet. Moreover, some of them, noticeably strcat, rely on the fact that the destination string can hold the entire string being appended onto the end. Although it might seem like you'll never make that sort of mistake, historically, problems based on accidentally writing off the end of an array in a function like strcat, have been a major problem。
故通常是經過strncpy等函數來進行操做。