本文出自 http://blog.csdn.net/shuangde800
首先保證安裝:
C語言連接MySQL數據庫
- MYSQL * mysql_init(MYSQL *);
- MYSQL* mysql_real_connect(MYSQL* connection,
- const char *server_host,
- const char *sql_user_name,
- const char *sql_password,
- const char *db_name,
- unsigned int port_number,
- const char *unix_socket_name,
- unsigned int flags);
指針connection必須指向已經被mysql_init初始化過的結構。
注意server_host既可以是主機名,也可以是IP地址。如果連接本地,可以制定localhost來優化。
sql_user_name和sql_password的含義和它們的字面意思一樣。如果登錄名爲NULL,則假設登錄名爲當前Linux用戶的登錄ID,如果密碼爲NULL,則假設密碼爲空。
port_number和unix_socket_name應該分別爲0和NULL,除非你改變了MySQL安裝的默認設置。他們將默認使用合適的值。
最後,flags參數用來對一些定義的位模式進行OR操作,使得改變使用協議的某些特性。
如果無法連接,則返回NULL。mysql_error函數可以提供有幫助的信息。
3. 使用完連接,通常在程序退出前,要調用函數mysql_close;
mysql_close的函數定義:
- void mysql_close(MYSQL *connection);
連接MySQL的示例:
- #include <stdio.h>
- #include <stdlib.h>
- #include "mysql.h"
- int main (int argc, char *argv[]) {
- MYSQL *conn;
- // 步驟1: 初始化連接句柄
- conn = mysql_init(NULL);
- if (conn == NULL) { // 如果返回NULl說明初始化失敗
- printf("mysql_init failed!\n");
- return EXIT_FAILURE;
- }
- // 步驟2:實際進行連接
- // 參數分別爲,conn連接句柄,host是MySQL所在主機或地址,user用戶名,password密碼,database_name數據庫名,後面的都是默認
- conn = mysql_real_connect(conn, "host", "user", "password", "database_name", 0, NULL, 0);
- if (conn) { // 連接成功
- printf("Connection success!\n");
- } else {
- printf("Connection failed!\n");
- }
- // 步驟3: 退出前關閉連接
- mysql_close(conn);
- return 0;
- }
編譯和運行:
- gcc -I/usr/include/mysql test.c -L/usr/lib/mysql -lmysqlclient -o app
錯誤處理
錯誤處理的兩個函數:
- // 返回錯誤碼
- unsigned int mysql_errno(MYSQL *connection);
- // 返回錯誤詳細信息
- char* mysql_error(MYSQL *connection);
- #include <stdio.h>
- #include <stdlib.h>
- #include "mysql.h"
- #include "errmsg.h"
- #include "mysqld_error.h"
- void Error(MYSQL* conn) {
- printf("Connection error %d: %s\n", mysql_errno(conn), mysql_error(conn));
- }
- int main (int argc, char *argv[]) {
- MYSQL conn; // 是變量而不是指針
- mysql_init(&conn); // 注意取地址符&
- if (mysql_real_connect(&conn, "192.168.137.246", "root", "123456", "test", 0, NULL, 0)) {
- printf("Connection success!\n");
- mysql_close(&conn);
- } else {
- fprintf(stderr, "Connection failed!\n");
- if (mysql_errno(&conn)) {
- fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&conn), mysql_error(&conn));
- }
- }
- return EXIT_SUCCESS;
- }