Linux系統(tǒng)中的C語(yǔ)言與MySQL的結(jié)合,可以實(shí)現(xiàn)強(qiáng)大的數(shù)據(jù)庫(kù)操作功能。使用MySQL數(shù)據(jù)庫(kù)能夠方便地存儲(chǔ)、管理數(shù)據(jù),而C語(yǔ)言作為一門高效的編程語(yǔ)言,可以實(shí)現(xiàn)各種數(shù)據(jù)處理、邏輯運(yùn)算等操作。
//連接MySQL數(shù)據(jù)庫(kù) MYSQL mysql; mysql_init(&mysql); if(mysql_real_connect(&mysql, "localhost", "root", "password", "database_name", 0, NULL, 0) == NULL) { printf("Error connecting to database: %s\n", mysql_error(&mysql)); exit(0); } //創(chuàng)建表 char *create_table = "CREATE TABLE IF NOT EXISTS users (id INT NOT NULL AUTO_INCREMENT, username VARCHAR(255) NOT NULL, email VARCHAR(255), PRIMARY KEY(id));"; if(mysql_query(&mysql, create_table)) { printf("Error creating table: %s\n", mysql_error(&mysql)); exit(0); } //插入數(shù)據(jù) char *insert_data = "INSERT INTO users (username, email) VALUES ('user1', 'user1@example.com');"; if(mysql_query(&mysql, insert_data)) { printf("Error inserting data: %s\n", mysql_error(&mysql)); exit(0); } //查詢數(shù)據(jù) MYSQL_RES *result; MYSQL_ROW row; char *select_data = "SELECT * FROM users WHERE id=1;"; if(mysql_query(&mysql, select_data)) { printf("Error selecting data: %s\n", mysql_error(&mysql)); exit(0); } result = mysql_store_result(&mysql); if(result == NULL) { printf("Error storing result: %s\n", mysql_error(&mysql)); exit(0); } row = mysql_fetch_row(result); if(row != NULL) { printf("%s %s\n", row[1], row[2]); } //關(guān)閉連接 mysql_close(&mysql);
以上代碼演示了連接MySQL數(shù)據(jù)庫(kù)、創(chuàng)建表、插入數(shù)據(jù)和查詢數(shù)據(jù)的基本操作。在實(shí)際應(yīng)用中,還可以使用C語(yǔ)言和MySQL的API實(shí)現(xiàn)更復(fù)雜的操作和查詢。