首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

Ubuntu 安裝 MySQL 與 C/C++ 程式存取範例(圖文)

     編輯:MySQL 綜合教學

Ubuntu 快速安裝 MySQL 並以 C 程式驗證連線

三條指令完成安裝,附原始碼編譯執行驗證。

1. 安裝套件

sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysqlclient-dev

安裝過程會提示設定 root 密碼,請記牢。

2. 驗證安裝

sudo netstat -tap | grep mysql
# 出現 LISTEN 狀態的 mysql socket 即成功

3. 登入並操作

mysql -u root -p
SHOW DATABASES;
USE mysql;
SHOW TABLES;

登入畫面 show tables 結果

4. C 程式存取範例(實現 SHOW TABLES)

#include 
#include 
#include 

int main() {
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char *server = "localhost";
    char *user = "root";
    char *password = "mima";      // 修改為你的密碼
    char *database = "mysql";

    conn = mysql_init(NULL);
    if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }

    if (mysql_query(conn, "SHOW TABLES")) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }

    res = mysql_use_result(conn);
    printf("MySQL Tables in mysql database:\n");
    while ((row = mysql_fetch_row(res)) != NULL) {
        printf("%s \n", row[0]);
    }

    mysql_free_result(res);
    mysql_close(conn);
    printf("finish! \n");
    return 0;
}

5. 編譯與執行

g++ -Wall mysql_test.cpp -o mysql_test -lmysqlclient
./mysql_test

程式執行結果

輸出結果與手工執行 SHOW TABLES 一致,驗證連線庫正常。

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