在使用C語(yǔ)言進(jìn)行數(shù)據(jù)處理時(shí),常常需要?jiǎng)?chuàng)建數(shù)據(jù)表來(lái)存儲(chǔ)和管理數(shù)據(jù)。本文將介紹如何使用C語(yǔ)言從Excel和MySQL中創(chuàng)建數(shù)據(jù)表。
從Excel創(chuàng)建數(shù)據(jù)表
#include#include #include int main() { FILE *fp; char line[1024]; char *token; int i = 0; fp = fopen("data.xlsx", "r"); if(!fp) { printf("File not found!\n"); exit(1); } printf("CREATE TABLE table_name (\n"); // 讀取Excel表格的第一行,即數(shù)據(jù)表的字段名 fgets(line, 1024, fp); token = strtok(line, ","); while (token) { printf("\t%s varchar(255),\n", token); token = strtok(NULL, ","); } printf(");\n"); fclose(fp); return 0; }
從MySQL創(chuàng)建數(shù)據(jù)表
#include#include #include int main() { MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } if (mysql_real_connect(con, "localhost", "username", "password", NULL, 0, NULL, 0) == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } if (mysql_query(con, "CREATE DATABASE database_name")) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } if (mysql_query(con, "USE database_name")) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } if (mysql_query(con, "CREATE TABLE table_name (" "id INT NOT NULL AUTO_INCREMENT," "column1 VARCHAR(255) NOT NULL," "column2 INT NOT NULL," "column3 DATE," "PRIMARY KEY (id))")) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } mysql_close(con); return 0; }