I'm trying to create a SQLite database in Qt. This is the code that I have:
#include <QtCore/QCoreApplication>
#include <QtSql/QSqlDatabase>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:\\Users\\Tanner\\Desktop\\db.sqlite");
return a.exec();
}
However, it doesn't work. This is the output I receive:
C:\Users\Tanner\qt\sqltest-build-desktop..\sqltest\main.cpp:8: error: undefined reference to `imp__ZN12QSqlDatabase17defaultConnectionE'
C:\Users\Tanner\qt\sqltest-build-desktop..\sqltest\main.cpp:8: error: undefined reference to `imp__ZN12QSqlDatabase11addDatabaseERK7QStringS2_'
C:\Users\Tanner\qt\sqltest-build-desktop..\sqltest\main.cpp:8: error: undefined reference to `imp__ZN12QSqlDatabaseD1Ev'
C:\Users\Tanner\qt\sqltest-build-desktop..\sqltest\main.cpp:9: error: undefined reference to `imp__ZN12QSqlDatabase15setDatabaseNameERK7QString'
C:\Users\Tanner\qt\sqltest-build-desktop..\sqltest\main.cpp:11: error: undefined reference to `imp__ZN12QSqlDatabaseD1Ev'
C:\Users\Tanner\qt\sqltest-build-desktop..\sqltest\main.cpp:11: error: undefined reference to `imp__ZN12QSqlDatabaseD1Ev'
:-1: error: collect2: ld returned 1 exit status
I'm sure that I'开发者_StackOverflow中文版m doing something wrong as this is the first time I have tried to work with a database in C++/Qt. Any help in creating a database is greatly appreciated! I added an extra slash in the filepath because the compiler kept complaining about character escaping. Could the the extra slashes have anything to do with it? If so, how can I enter the path without it thinking I'm trying to escape the next character.
After not getting it to work, I checked with the Qt Community Forum and it seems that all I was missing was
QT += sql
in the .pro file
Here is the forum post: http://developer.qt.nokia.com/forums/viewthread/8262/
The errors you're seeing are not compiler errors, but linker errors. The error itself is not related to SQLite, but to Qt. You most likely don't link against QtSql4.lib (the 4 might be a different version number). Doing that will most likely make the errors you're seeing go away.
As an answer to your comment/question, you don't (on your application level) have to worry about SQLite at all. Since you use Qt's SQL functionality, this will be taken care of (and "hidden") by Qt. Qt uses so called database drivers which are essentially plugins it loads based on what you have specified in your code. So an SQLite driver in your case.
If this driver has not been created when you installed Qt, you might have to build it yourself. You can follow the instructions you can find in the link I have provided above.
P.s. you have correctly handled the "character escaping" issue. This is not the cause of your current problems.
精彩评论