【问题标题】:how to connecting to sqlite by qt and run it on android如何通过q​​t连接到sqlite并在android上运行
【发布时间】:2023-04-11 06:03:01
【问题描述】:

我想连接 sqlite 数据库并编写一个 Android 应用程序。
但是,当我运行应用程序时,我给出了一个错误:数据库未打开。

#include "csqlconnect.h"
#include <QFile>
#include <QSqlQuery>
#include <QMessageBox>
#include <QDebug>
#include <QSql>
#include <QSqlError>
#include <QSqlTableModel>
#include <QSqlRecord>

CSqlConnect::CSqlConnect()
{
db = QSqlDatabase::addDatabase( "QSQLITE","MyConnection" );
QFile dfile("./myfile.sqlite");
bool dbf=dfile.exists();
if (!dbf)
{
QFile::copy("assets:/myfile.sqlite", "./myfile.sqlite");
QFile::setPermissions("./myfile.sqlite",QFile::WriteOwner |    QFile::ReadOwner);
}
db.setDatabaseName( "myfile.sqlite" );
bool open=db.open();
if(!open)
{
QMessageBox::warning(0, "Failed to connect!", "Error connecting to     database: "+db.lastError().driverText());
   // qDebug()<<"Failed!!!!";
}

if(open)
{
QSqlQuery query;
query.exec("create table person "
      "(id integer primary key, "
      "firstname varchar(20), "
      "lastname varchar(30), "
      "age integer)");

}

 QSqlQuery query2;

query2.prepare("INSERT INTO person (id,firstname,lastname,age)VALUES(:ID,:FIRSTNAME,:LASTNAME,:AGE)"); query2.bindValue(":ID",1); query2.bindValue(":FIRSTNAME","ali"); query2.bindValue(":LASTNAME","alavi"); query2.bindValue(":AGE",24); 查询2.exec(); QSqlTableModel 模型; model.setTable("人"); 模型.选择(); QSqlRecord 记录=model.record(0); result=record.value("firstname").toString(); }

QString CSqlConnect::getValue()
{
   return result;
}

CSqlConnect::~CSqlConnect()
{
db.close();
}

【问题讨论】:

    标签: android database qt sqlite connection


    【解决方案1】:

    您正在尝试在当前工作目录 (./myfile.sqlite) 中创建 SQLite 文件,该文件很可能无法从 Android 上的应用程序中写入。

    最好从QStandardPaths明确获取可写路径:

    const auto path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    
    errno = 0;
    if (!QDir(path).mkpath()) {
        // return error, get details from strerror(errno)
        …
        return;
    }
    
    db.setDatabaseName(path + QStringLiteral("/myfile.sqlite"));
    if (!db.open()) {
       // handle error
       …
       return;
    }
    
    …
    

    【讨论】:

    • 令人惊讶的是,在谷歌中很难找到这个答案。在来这里之前浪费了2个小时。对于那些满怀愤怒和沮丧来到这里的其他人:现在只需使用 #ifdef Q_OS_ANDROID 就可以了。
    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 2012-03-31
    • 2020-06-24
    • 2016-01-04
    • 2018-07-27
    • 2019-11-12
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多