首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

Ubuntu 下 MySQL 安裝與 C/C++ 開發完整教程

     編輯:MySQL 資料庫相關知識

APT 快速安裝

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

安裝過程會提示設定 root 密碼,請妥善保存。

驗證安裝

# 檢查端口監聽
sudo netstat -tap | grep mysql
# 輸出含 LISTEN 狀態即成功

# 登入測試
mysql -u root -p
mysql> SHOW DATABASES;

MySQL 登入

基本操作演示

USE mysql;
SHOW TABLES;

SHOW TABLES

C/C++ 訪問 MySQL 示例

#include 
#include 
#include 

int main() {
    MYSQL *conn = mysql_init(NULL);
    MYSQL_RES *res;
    MYSQL_ROW row;

    char *server = "localhost";
    char *user = "root";
    char *password = "your_password";
    char *database = "mysql";

    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;
}

編譯與運行

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

程序運行結果

常見問題

  • 編譯找不到 mysql.h:確認已裝 libmysqlclient-dev
  • 連接失敗:檢查 bind-address、防火牆、密碼正確性
  • 中文亂碼:連接後執行 SET NAMES utf8mb4
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved