sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysqlclient-dev
/usr/include/mysql/mysql.h
connect_to_mysql_v0.0.c
#include
#include
#include
#include
#include"/usr/include/mysql/mysql.h"
int main(){
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char server[] = "localhost";
char user[] = "root";
char password[] = "123456";
char database[] = "knowledge";
conn = mysql_init(NULL);
if(mysql_real_connect(conn, server, user, password, database, 3306, NULL, 0)){
printf("成功连接数据库knowledge\n");
}
if(!mysql_real_connect(conn, server, user, password, database, 3306, NULL, 0)){
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
if(mysql_query(conn, "select * from knowledge")){
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
printf("MYSQL Tables: \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;
}
gcc connect_to_mysql_v0.0.c -o cc -lmysqlclient
connect_to_mysql_v0.0.c
#include
#include
#include
#include
#include"/usr/include/mysql/mysql.h"
int main(int argc, char **argv){
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char server[] = "localhost";
char user[] = "root";
char password[] = "123456";
char database[] = "knowledge";
conn = mysql_init(NULL);
if(mysql_real_connect(conn, server, user, password, database, 3306, NULL, 0)){
printf("成功连接数据库knowledge\n");
}else{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
// if(!mysql_real_connect(conn, server, user, password, database, 3306, 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);
// }
if(mysql_query(conn, "select * from knowledge")){
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}else{
res = mysql_use_result(conn);
printf("MYSQL Tables: \n");
while((row=mysql_fetch_row(res)) != NULL){
printf("\nQuestion: %s", row[0]);
printf("\tAnswer: %s", row[1]);
}
}
mysql_free_result(res);
mysql_close(conn);
printf("\nfinish!");
return 0;
}
gcc connect_to_mysql_v0.0.c -o cc -lmysqlclient
【参考文献】
[1]https://www.cnblogs.com/zhuyp1015/p/3561470.html
[2]https://blog.csdn.net/qq_38422690/article/details/78660454