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

用 GCC 批量建立 MySQL 資料庫與表結構:C 語言自動化腳本實戰

     編輯:MySQL 資料庫相關知識

腳本架構:主程式 + 表清單頭文件

主程式 my.c

// MySQL Database Create 1/13/2001. Netkiller Chen
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern char *table_file[];  // 來自 table.h

void showme() {
  printf("-----------------------------------------------------------\n");
  printf(" I am Netkiller Chen.\n");
  printf(" I am a programmer and system&net manager.\n");
  printf(" I am glad to be friend with you!\n");
  printf("-----------------------------------------------------------\n");
}

void address() {
  printf(" ----------------------------------\n");
  printf("| newtech@sina.com |\n");
  printf("| OICQ:13721218 |\n");
  printf("| 1/13/2001 |\n");
  printf("----------------------------------\n");
}

int main() {
  char host[16], sid[15], pwd[15];
  char mydatabase[256], mysqltable[256];
  int i = 0, max_table_num = 4, db, status;

  system("clear");
  showme();

  printf("MySQL host:");  scanf("%s", host);
  printf("Root user:");   scanf("%s", sid);
  printf("Password:");    scanf("%s", pwd);
  printf("Loading........ ");

  while (table_file[i]) {
    sprintf(mydatabase, "echo \"create database %s\" | mysql -h%s -u%s -p%s", table_file[i], host, sid, pwd);
    sprintf(mysqltable, "mysql -h%s -u%s -p%s %s < %s.sql", host, sid, pwd, table_file[i], table_file[i]);

    db = system(mydatabase);
    status = system(mysqltable);

    printf("%s ", table_file[i]);
    if (db == 0 && status == 0) printf(" Install [ OK ] ");
    else printf(" Install [ :( ] ");
    i++;
  }
  address();
  return 0;
}

表清單 table.h

char *table_file[] = {
  "alxx", "bcxx", "fycx", "fyxwxx", "fyzxxx",
  "hwzx", "lhzxxx", "xxdexx", "xxdsxx", "xxfgxx",
  "xxglxx", "xxgsxx", "xxhmbxx", "xxhtxx", "xxjbxx",
  "xxltxx", "xxzwxx", "xxzx", NULL
};

使用流程

  1. 將 .sql 建表腳本放入 /root/mygcc/,檔名對應 table.h 陣列(如 alxx.sql)。
  2. 編譯:gcc my.c -o my
  3. 執行:./my,依提示輸入主機、用戶、密碼,自動批量建庫建表。

教學價值

程式雖簡單,但涵蓋指標、陣列、頭文件引用、NULL 終止、system() 呼叫、字串格式化等 C 語言核心概念,極適合 GCC 入門者參考。實際專案中可擴展為參數化配置、錯誤碼詳細判斷、平行執行等企業級部署腳本。

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