dmysql 是一個極簡 C 語言 MySQL 客戶端封裝,僅三個公開函數,適合嵌入式、CGI、高效能服務端直接呼叫。
/* 連線資訊 */
typedef struct _dmysql_info {
char *host; // 伺服器位址
char *user; // 用戶名
char *pswd; // 密碼
char *dbbs; // 資料庫名
} dmysql_info;
/* 單一欄位值 */
typedef struct _dmysql_record {
char *s_str;
} dmysql_record;
/* 單列(多欄位) */
typedef struct _dmysql_row {
dmysql_record *s_record;
} dmysql_row;
/* 結果集 */
typedef struct _d_mysql_res {
int row; // 列數
int field; // 欄位數
dmysql_row *s_row; // 列陣列
} dmysql_res;
#define DMYSQL_QUERY_OKAY 0
#define DMYSQL_SELECT_OKAY 0
#define DMYSQL_CONNECT_ERROR -1
#define DMYSQL_INIT_ERROR -2
#define DMYSQL_QUERY_ERROR -3
#define DMYSQL_RES_ERROR -4
| 函數 | 用途 | 參數 | 回傳 |
|---|---|---|---|
dmysql_query | 執行非查詢 SQL(INSERT/UPDATE/DELETE/DDL) | const char *sql, const dmysql_info info | 0 成功,負值錯誤碼 |
dmysql_select | 執行查詢並回傳結果集 | dmysql_res **out, const char *sql, const dmysql_info info | 0 成功,負值錯誤碼 |
dmysql_free | 釋放結果集記憶體 | dmysql_res *res | 無 |
# 解壓後
make
make install # 複製 libdmysql.so/.a 至 /usr/local/lib,頭文件至 /usr/local/include
# 專案編譯連結
gcc -Wall -O3 -o myapp main.c -ldmysql `mysql_config --libs --cflags`
#include
#include
int main(void) {
dmysql_info db = {
.host = "127.0.0.1",
.user = "root",
.pswd = "",
.dbbs = "mysql"
};
const char *grant_sql = "GRANT ALL ON *.* TO 'dorainm'@'127.0.0.1' IDENTIFIED BY '******';";
const char *select_sql = "SELECT `user`,`host`,`password` FROM `user`;";
dmysql_res *res = NULL;
int i, j;
// 執行 GRANT
if (dmysql_query(grant_sql, db) != DMYSQL_QUERY_OKAY) {
fprintf(stderr, "GRANT failed\n");
return 1;
}
// 查詢
int rc = dmysql_select(&res, select_sql, db);
printf("select out: %d\n", rc);
if (rc == DMYSQL_SELECT_OKAY && res) {
for (i = 0; i < res->row; i++) {
for (j = 0; j < res->field; j++) {
printf("%s\t", ((res->s_row + i)->s_record + j)->s_str);
}
printf("\n");
}
dmysql_free(res);
}
return 0;
}
select out: 5
root localhost %^$#!@%*&!
root desktop.dorainm.org %^$#!@%*&!
desktop.dorainm.org %^$#!@%*&!
localhost %^$#!@%*&!
dorainm 127.0.0.1 %^$#!@%*&!
malloc,呼叫端務必呼叫 dmysql_free。dmysql_error() 回傳詳細訊息。dmysql_prepare、dmysql_bind_param、dmysql_execute 介面。dmysql_info 或加鎖。