1. 安装mysql client包
sudo apt-get install libmysqlclient15-dev
2. 编写C程序
#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"
int main(int argc, char *argv[])
{
MYSQL *conn_ptr;
conn_ptr = mysql_init(NULL);
if (!conn_ptr)
{
fprintf(stderr, "mysql_init failed\n");
return EXIT_FAILURE;
}
conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "mysql", "mysql", 0, NULL, 0);
if (conn_ptr)
{
printf("Connection success\n");
}
else
{
printf("Connection failed\n");
}
mysql_close(conn_ptr);
return EXIT_SUCCESS;
}
#include <stdio.h>
#include "mysql.h"
int main(int argc, char *argv[])
{
MYSQL *conn_ptr;
conn_ptr = mysql_init(NULL);
if (!conn_ptr)
{
fprintf(stderr, "mysql_init failed\n");
return EXIT_FAILURE;
}
conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "mysql", "mysql", 0, NULL, 0);
if (conn_ptr)
{
printf("Connection success\n");
}
else
{
printf("Connection failed\n");
}
mysql_close(conn_ptr);
return EXIT_SUCCESS;
}
3. 编译程序
gcc -I/usr/include/mysql connect1.c -L/usr/lib/mysql -lmysqlclient -o connect1
4. 执行
./connect1
5. 运行结果
Connection success