linux通过c语言编程访问远程mysql

时间:2022-04-24 09:15:39
首先开启远程mysql访问允许
mysql -u root -p
mysql>use mysql;
mysql>select 'host' from user where user='root';
mysql>update user set host = '%' where user ='root';
mysql>flush privileges;
mysql>select 'host'   from user where user='root';

到mysql的官网下载 Connector/C (libmysql) A client library for C development.

把下载的文件解压
tar xvzf mysql-connector-c-6.0.2-linux-glibc2.3-x86-32bit.tar.gz

把解压以后的include文件夹里的文件拷贝到/usr/include/mysql文件夹下
mkdir /usr/include/mysql
cp -rf include/* /usr/include/mysql

把解压以后的lib文件夹里的文件放到/usr/lib文件夹下
cp lib/* /usr/lib/

编写测试程序
#include <stdio.h>
#include <stdlib.h>
#include "mysql/mysql.h"

int main(void)
{
const char *host = "59.71.72.133";
const char *user = "root";
const char *pass = "";
const char *db = "mysql";
/* 定义mysql变量 */
MYSQL mysql;
MYSQL_RES *rs;
MYSQL_ROW row;
mysql_init(&mysql); /* 初始化 */
/* 连接数据库 */
if (!mysql_real_connect(&mysql, host, user, pass, db, 0, NULL, 0))
{
printf("数据库连接失败: %s\n", mysql_error(&mysql));
} else {
printf("数据库连接成功!\n");
}
char *sql = "select host,user from user order by rand()";
if (mysql_query(&mysql, sql)!=0)
{ /* 查询 */
printf( "%s", mysql_errno(&mysql), mysql_error(&mysql));
}
rs = mysql_store_result(&mysql); /* 获取查询结果 */
while ((row = mysql_fetch_row(rs)))
{ /* 获取每一行记录 */
printf( "%s---%s", row[0], row[1]);
}
mysql_free_result(rs); /* 释放结果集 */
mysql_close(&mysql); /* 关闭连接 */
return 1;
}



用以下命令使用 GCC 编译 这个 C源文件.
gcc -o mysqltest -g mysqltest.c -lmysqlclient

./mysqltest