先安裝mysql
代碼:sudo apt-get install mysql-server mysql-client
再裝開發包代碼:sudo apt-get install libmysqlclient15-dev
安裝完以後,C代碼裡添加標頭檔代碼:#include <mysql.h>
編譯方法:代碼:gcc $(mysql_config --cflags) xxx.c -o xxx $(mysql_config --libs)
可以用以下代碼測試一下代碼:/* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = ""; /* 此處改成你的密碼 */
char *database = "mysql";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
/* output table name */
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
會輸出現有資料庫和表內容。