MySQL connector/C++ 连接mysql效率低下解决

这个问题 说解决也不算是被解决了,只能是让数据库插入的时候不会有像直接插入一样有那么多的问题了。。

我的解决方法是 开启mysql的事务。

开始我也不知道是不是我的mysql配置优化的问题(WAMP统一安装,无限默认下一步的)。

在用PHP测试的时候插入的水平也和c++的效率是一个样的1秒钟才插入不到50条数据。

然后朋友的php lamp环境插入1w条数据也只用了0.01秒。

在网上百度很久 没有百度到,在google上搜索到了一文章 跟我遇见的问题是一样的,然后 他是通过事务来处理大批量数据插入的。

直接代码:

#include <statement.h>  
#include<windows.h>
#include "mysql_connection.h" 
#include "mysql_driver.h" 

#include <cppconn/driver.h> 
#include <cppconn/exception.h> 
#include <cppconn/resultset.h> 
#include <cppconn/statement.h> 
#include <cppconn/prepared_statement.h> 


using namespace sql;
using namespace std;  
void RunConnectMySQL()   
{  
	mysql::MySQL_Driver *driver;  
	Connection *con;  
	Statement *state;  
	ResultSet *result;  
	// 初始化驱动  
	driver = sql::mysql::get_mysql_driver_instance();  
	// 建立链接
	try{
	con = driver->connect("tcp://127.0.0.1:3306", "root", "");  //注意这里用的是TCP,开始使用的是http连接了很久都没有连接上的
	}
	catch(SQLException &e){

		cout<<"数据库连接失败"<<endl;
		return ;
	}
	state = con->createStatement();  
	state->execute("use test");  
	LARGE_INTEGER BegainTime ; 
	LARGE_INTEGER EndTime ; 
	LARGE_INTEGER Frequency ;
	QueryPerformanceFrequency(&Frequency);
	QueryPerformanceCounter(&BegainTime) ; //计算代码执行时间的
	
	

	
	string sql = " INSERT INTO testin VALUES (NULL ,'xxxx','23','text') ;";
		con->setAutoCommit(false);
	for(int  i= 0  ; i <= 10000;i++)
	{
	try{
		
		state->execute(sql);
	
	}catch(sql::SQLException &e)
		{
			cout<<"ERROR : "<<e.getSQLState()<<endl;
		}
		if(!(i%10))
			cout<<i<<endl;
	}//
		con->commit();
		con->setAutoCommit(true);
	QueryPerformanceCounter(&EndTime) ;
	cout << ( EndTime.QuadPart - BegainTime.QuadPart )*1000 / Frequency.QuadPart ;
	
	delete state;  
	delete con;  
}  
int main(int argc, char* argv[])  
{  
	RunConnectMySQL();  
	getchar();  
	return 0;  
}
在我的机器上跑1w条插入数据 用了1.6s

然后 还没有解决的问题 就是 如何让MYSQL connector 如何解决能够同时执行多条sql语句的问题。网上搜索的目前还不靠谱 - -

猜你喜欢

转载自blog.csdn.net/kyou007/article/details/8116061