(一) 前置条件:
(1) Linux 已经安装好 mysql 数据库;
(2) Linux 已经安装了 gcc 编译器;
(二)数据库准备:
为了便于描述,假设数据库的 root 用户密码为 root。
(1) 以 root 用户登陆数据库
#mysql -u root –p
mysql>
(2) 创建数据 testdb
mysql> create database testdb;
(3) 创建表
mysql> use testdb;
mysql> create table user_info ('user_id" NOT NULL,
'usr_name NOT NULL,
PRIMARY KEY ('user_id'));
(4) 向表中插入一条记录
mysql> insert into usr_info(user_id, user_name) values(1, 'abc');
Source Code:
#include <stdio.h>
#include <string>
#include <mysql.h>
#include <pthread.h>
using namespace std;
struct SqlStr
{
MYSQL* mpMysql;
string mStr;
};
void* RunSql(void* ipStr)
{
int hr = 0;
SqlStr* lpSqlStr = (SqlStr *)ipStr;
if (mysql_real_query(lpSqlStr->mpMysql, lpSqlStr->mStr.c_str(), (unsigned int)lpSqlStr->mStr.length()) == 0)
{
printf("query successful\n");
}
else
{
printf("query failed\n");
hr = -1;
}
return NULL;
}
void* DisplayTable(void* ipMysql)
{
int hr = 0;
int t;
MYSQL* lpMysql = (MYSQL *)(ipMysql);
string query("select * from user_info;");
if(mysql_real_query(lpMysql, query.c_str(),(unsigned int)query.length())==0){
printf("query successful\n");
}else{
printf("query failed\n");
hr = -1;
}
MYSQL_RES* res=mysql_store_result(lpMysql);
MYSQL_ROW row;
while(row=mysql_fetch_row(res))
{
for(t=0;t<mysql_num_fields(res);t++)
{
printf("%s\t",row[t]);
}
printf("\n");
}
return NULL ;
}
int main()
{
MYSQL mysql;
//char *query;
int t;
mysql_init(&mysql);
/*connection*/
if(!mysql_real_connect(&mysql,"localhost","root","root","dengzhi",0,NULL,0)){
printf("Connect failed\n");
return -1;
}else{
printf("Connect successful\n");
}
pthread_t ltDispThread;
if ( pthread_create(<DispThread, NULL, DisplayTable, &mysql) )
printf("Create thread error\n");
if ( pthread_join(ltDispThread, NULL) )
{
printf("error joining thread.\n");
return -1;
}
SqlStr lStr1;
lStr1.mpMysql = &mysql;
lStr1.mStr = string("insert into user_info values (2, 'def')");
pthread_t ltInsertThread;
if ( pthread_create(<InsertThread, NULL, RunSql, &lStr1) )
printf("Create thread error\n");
if ( pthread_join(ltInsertThread, NULL) )
{
printf("error joining thread.\n");
return -1;
}
mysql_free_result(res);
mysql_close(&mysql);
return 0;
}
编译:
gcc -o sqlconnect -g sqlconnect.c -I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient
调试: gdb ./sqlconnect