今天在看《Linux C 程序設計》8.3節,一下午終於調通了程序,記下來
1.創建並授權用戶
2.創建數據庫
3.敲代碼
下面的代碼來自《Linux C 程序設計》第四版
/*-----connect1.c-----以用戶rick和密碼secret來連接本機服務器上名爲foo的數據庫---------------------------*/
#include <stdlib.h>
#include <stdio.h>
#include <mysql/mysql.h>//原文爲 #include <mysql.h>無法通過編譯
int main(int argc, char *argv[]){
MYSQL *conn_ptr;
conn_ptr = mysql_init(NULL);
if(!conn_ptr) {
fprintf(stderr, "mysql_init failed\n");
return EXIT_FAILURE;
}
conn_ptr = mysql_real_connect(conn_ptr, "localhost", "rick", "secret", "foo", 0, NULL, 0);
if(conn_ptr) {
printf("connection success\n");
} else {
printf("connection failed\n");
}
mysql_close(conn_ptr);
return EXIT_SUCCESS;
}
說明:
1.編譯找不到 /usr/include/mysql/mysql.h,在終端運行
apt-get install libmysqlclient-dev
2.編譯找不到mysql_init(), mysql_real_connect(), mysql_close(),添加鏈接選項(函數實現的位置)
gcc connect1.c -o conn1 -l mysqlclient
3.eclipse-indigo 下編譯需要配置項目的編譯選項
右鍵項目--Properties--GCC C Linker--Libraries--(在-l欄添加 mysqlclient)
另外的例子:
http://blog.sina.com.cn/s/blog_494e45fe0100k9p8.html
http://blog.chinaunix.net/uid-20787846-id-1842214.html
當然最重要的還是
http://dev.mysql.com/doc/refman/5.5/en/c-api.html