在动态编译qt程序时,当把程序拷贝到目标机器上时,如果想要使数据库可以运行,必须在程序的同级目录下建立plugins/qsqldrivers 文件夹,然后把数据库插件放进去。但是当静态编译时,这一招就不管用了,可看见静态库下面的qsqldrivers里面没有dll文件,无法被动态加载。
解决这个问题的方法是,在.pro文件里添加QTPLUGIN+=qsqlite,这样就可以了。
文档如下:
The normal and most flexible way to include a plugin with an application is to compile it into a dynamic library that is shipped separately, and detected and loaded at runtime.
Plugins can be linked statically against your application. If you build the static version of Qt, this is the only option for including Qt's predefined plugins. Using static plugins makes the deployment less error-prone, but has the disadvantage that no functionality from plugins can be added without a complete rebuild and redistribution of the application.
QTPLUGIN += qjpeg \
qgif \
qkrcodecs
经过分析,qt里面数据库加载的原理是qsql的lib只是对各个数据库插件的一层封装,并不具体实现数据库的功能。各个数据库插件才是实现数据库底层功能的库。所以不要以为包含了lib下面的qsql.lib就可以实现数据库功能了。必须还要包含plugins下面的sqldriver