多线程连接MySql
来源:互联网 发布:lil pump 知乎 编辑:程序博客网 时间:2024/05/29 21:17
(一) 前置条件:
(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
- 多线程连接MySql
- Linux平台多线程连接MySQL细节赘述
- 使用python多线程连接mysql数据库
- Solaris10 下的多线程和Mysql多线程连接
- 多线程共享MySQL连接时,使用事务的危险!
- linux下多线程连接mysql(C语言)
- mysql C api 多线程多连接 客户端实现
- 多线程连接
- 【mysql】mysql多线程
- MYSQl 连接
- 连接MySQL
- mysql连接
- MySQL连接
- 连接MySQl
- 连接mysql
- MySQL连接
- 连接MySQL
- MySql连接
- Go项目的目录结构
- 回溯法求解01背包问题
- java.lang.RuntimeException: java.lang.ClassNotFoundException
- maven in action(十)maven项目建立和运行过程中可能的错误
- 对象引用(浅克隆和深克隆)
- 多线程连接MySql
- Android 中的样式与主题
- springmvc如何通过properties读取配置文件
- 解决百人牛牛在部分电脑中摸牌动画卡顿问题,摸牌时改全部刷新为局部刷新
- 八大排序算法之一直接插入排序(C语言)
- motion estimation
- ADO学习(一)基础理论
- celipse安装tomcat插件,找不到server选项
- go 语言学习网站