首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Ubuntu 上使用 C 語言連接 MySQL 資料庫完整教學

     編輯:關於C語言

環境部署:安裝 MySQL 服務與開發套件

本教學以 Ubuntu 11.10 為例,示範如何從零開始建立 C 語言存取 MySQL 的開發環境。

1. 安裝 MySQL 伺服器與客戶端

sudo apt-get install mysql-server mysql-client

2. 安裝 C 語言開發函式庫

編譯連結 MySQL 客戶端程式需安裝開發套件:

sudo apt-get install libmysqlclient15-dev

安裝開發套件畫面

建立測試資料庫與資料表

登入 MySQL 並建立資料庫

mysql -u rick -p
CREATE DATABASE foo;

登入 MySQL 畫面

建立 children 資料表並插入測試資料

CREATE TABLE children(
  childno int(11) NOT NULL auto_increment,
  fname varchar(30),
  age int(11),
  PRIMARY KEY (childno)
);

INSERT INTO children(childno,fname,age) VALUES(1,'Jenny',21);
INSERT INTO children(childno,fname,age) VALUES(2,'Andrew',17);
INSERT INTO children(childno,fname,age) VALUES(3,'Gavin',8);
INSERT INTO children(childno,fname,age) VALUES(4,'Duncan',6);
INSERT INTO children(childno,fname,age) VALUES(5,'Emma',4);
INSERT INTO children(childno,fname,age) VALUES(6,'Alex',15);
INSERT INTO children(childno,fname,age) VALUES(7,'Adrian',9);

建立資料表與插入資料

C 語言連線測試程式

connect1.c:基本連線驗證

#include <stdlib.h>
#include <stdio.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", "rick", "foo", 0, NULL, 0);
    if (conn_ptr)
        printf("Connection success\n");
    else
        printf("Connection failed\n");

    mysql_close(conn_ptr);
    return EXIT_SUCCESS;
}

連線成功畫面

編譯關鍵: 必須指定標頭檔路徑、函式庫路徑並連結 mysqlclient 函式庫。
若未安裝 libmysqlclient15-dev,編譯時會出現找不到 mysql.h 的錯誤。

缺少開發套件的編譯錯誤

執行 SQL 資料操作範例

插入資料並檢查影響行數

#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"

int main() {
    MYSQL my_connection;
    int res;

    mysql_init(&my_connection);
    if (mysql_real_connect(&my_connection, "localhost", "rick", "rick", "foo", 0, NULL, 0)) {
        printf("Connection success\n");
        // 執行 INSERT 語句
        res = mysql_query(&my_connection, "INSERT INTO children(fname,age) VALUES('Ann',3)");
        if (!res)
            printf("Inserted %lu rows\n", (unsigned long)mysql_affected_rows(&my_connection));
        else
            fprintf(stderr, "Insert error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection));

        mysql_close(&my_connection);
    } else {
        fprintf(stderr, "Connection failed\n");
        if (mysql_errno(&my_connection))
            fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection));
    }
    return EXIT_SUCCESS;
}

插入資料執行結果

資料表驗證結果

重要提醒: mysql_affected_rows() 回傳的是實際被修改的行數,而非 WHERE 條件符合的行數。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved