概述
- MySQL安装时,请确保安装了MySQL-server、MySQL-client、MySQL-devel。
安装过程请参考:https://blog.51cto.com/weiyuqingcheng/5753459
- 整理MySQL include目录
# 创建MySQL include目录
mkdir /usr/include/mysql
# 将MySQL include复制到放入创建的文件夹中
cp -r /usr/src/debug/mysql-8.0.30/mysql-8.0.30/include/ /usr/include/mysql
- 创建MySQL C库软连接
cd /usr/lib64/mysql
ln -s /usr/lib64/mysql/libmysqlclient.so.18.1.0 /usr/lib64/mysql/libmysqlclient.so
4.创建C项目(我是用的QtCreator创建的)
# 引入MySQL include目录
INCLUDEPATH += /usr/include/mysql
# 链接MySQL动态链接库
LIBS += -L/usr/lib64/mysql -lmysqlclient
- 编写代码
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
int main()
{
MYSQL *pMySql = mysql_init( NULL );
mysql_real_connect( pMySql, "192.168.232.162", "test", "xxxx", "test", 3306, NULL, 0 );
if( !pMySql )
{
printf( "Connect mysql error: %s\n", mysql_error( pMySql ) );
return -1;
}
//query
char strSql[] = "select * from TABLE_DESC;";
int nRet = mysql_real_query( pMySql, strSql, sizeof( strSql ) );
if( nRet != 0 )
{
printf( "Query failed: %s\n", mysql_error( pMySql ) );
return -1;
}
//print result
MYSQL_RES* pResult = mysql_store_result( pMySql );
int nRowNum = mysql_num_rows( pResult );
int nColumnNum = mysql_num_fields( pResult );
printf( "Row num: %d, Column num: %d\n", nRowNum, nColumnNum );
MYSQL_ROW rowData;
while( ( rowData = mysql_fetch_row( pResult ) ))
{
for( int n = 0; n < nColumnNum; n++ )
{
printf( "%s\t", rowData[ n ] );
}
printf( "\n" );
}
mysql_free_result( pResult );
mysql_close( pMySql );
return 0;
}
遇到的问题
- 问题:测试代码时,运行到 mysql_real_query() 函数时,报错:mysql server has gone away。
- 原因:未安装 mysql-community-devel-8.0.30-1.el7.x86_64.rpm