C++ 如何在 Qt 中创建 SQLite 数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27844759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a SQLite database in Qt
提问by user3009135
I am trying to create a SQLite database in Qt. Here is my code:
我正在尝试在 Qt 中创建一个 SQLite 数据库。这是我的代码:
QDir databasePath;
QString path = databasePath.currentPath()+"myDb.db";
QSqlDatabase dbConnection = QSqlDatabase:addDatabase("QSQLITE");
db.setDatabaseName(path);
db.open();
There are no errors when running the code, but I can't find the database I created in the path I defined. Does this actually create the database or does it just do some initialization?
运行代码时没有错误,但是在我定义的路径中找不到我创建的数据库。这实际上是创建数据库还是只是进行一些初始化?
If it does not create the database then how do I create the database within the application itself? (I am not talking about insertion.)
如果它不创建数据库,那么我如何在应用程序本身内创建数据库?(我不是在谈论插入。)
回答by Kosovan
You should also create query which will create not empty database and use correct name of variable(in your code you use dbConnection
firstly and after that - db
. For example:
您还应该创建查询,该查询将创建非空数据库并使用正确的变量名称(在您dbConnection
首先使用的代码中,然后使用- db
。例如:
QString path = "path";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection
db.setDatabaseName(path);
db.open();
QSqlQuery query;
query.exec("create table person "
"(id integer primary key, "
"firstname varchar(20), "
"lastname varchar(30), "
"age integer)");