• 6143阅读
  • 4回复

高手进来, 关于多线程连MYSql的 [复制链接]

上一主题 下一主题
离线songzhao831
 

只看楼主 正序阅读 楼主  发表于: 2014-06-19
— 本帖被 songzhao831 执行加亮操作(2014-06-19) —
我现在有个多线程连mysql的项目, 开发过程中遇到一个问题
就是怎么样打开操作数据的问题, 下面有几种方案, 分别都遇到问题.
1. 在main中打开数据库, 在其它线程中直接用query去操作, 问题出来了, 总会出现sql连接lost mysql connect. 网上说系统配置timeout或者size大小不对.

2. 每个线程中自己打开数据库, 但总出现作用域的问题. 一直提示'qt_sql_default_connection' is still in use.


3. 每次操作中打开数据库. 还没测试, 但这样会不会系统太慢....




有过这种线程重入操作数据库经验的来谈谈....

离线tadpole999

只看该作者 4楼 发表于: 2015-01-28
sevencat   能不能讲解哈你的搞法?谢谢。
离线sevencat

只看该作者 3楼 发表于: 2014-06-19
自己封装一个mysql的类,我在项目里是自己写的一个,一个写的mysql连接,每个线程有自己的读连接,用的线程局部变量,在访问写连接的时候需要加锁。
战争就是和平,自由就是奴役,愚味就是力量
离线songzhao831

只看该作者 2楼 发表于: 2014-06-19
方案一还真是可行, 这个相当于做了一个全局的连接, 随时可供使用, 便测试中(我开了100个线程同时去访问), 在第五个结束时, 这个连接就断开了, 时间大约是在几百毫秒内. 估计是这期间访问的数据量超出了数据库的承受.
方案二中. 我是在这个线程结束是删除这个dabase的连接. 在删除时出了这个错, 查了好几天, 发现说是有作用域的问题. 就是类似这样
{
  opendabase
  query
}
delete connection.

扩号内的作用域, 出了这个作用域才能删除连接.  这个使用也太受限了. 里面有很多函数要用这个连接来访问.  所以我试着在外面使用这个类的地方结束后删除. 但就出这个错. still in use.
离线dbzhang800

只看该作者 1楼 发表于: 2014-06-19
这个,自己高亮自己的问题,这个不好吧?你不能用一个线程做这个事情,其他线程去和这个工作线程通讯么?


不了解数据库,不过Qt自带的Manual中,对于QtSql和thread是这么说:

A connection can only be used from within the thread that created it. Moving connections between threads or creating queries from a different thread is not supported.

In addition, the third party libraries used by the QSqlDrivers can impose further restrictions on using the SQL Module in a multithreaded program. Consult the manual of your database client for more information

也就是你的方案1是不可行的。

至于方案2:Qt代码manual中

If connectionName is not specified, the new connection becomes the default connection for the application, and subsequent calls to database() without the connection name argument will return the default connection. If a connectionName is provided here, use database(connectionName) to retrieve the connection.

Warning: If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this function more than once without specifying connectionName, the default connection will be the one replaced.

至少说明,你不能同时创建相同的连接,和是否多线程没关。
快速回复
限100 字节
 
上一个 下一个