Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

Qt Android SQLite: No such table

Creating an test app only with 2 buttons to check sqlite database on android. Database added on proj files.

Button db connect

void MainWindow::on_pushButton_clicked()
{
QSqlDatabase db;
QString dbName = "test.db";
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbName);
if(!db.open())
    ui->textEdit_2->setText("no");
else  
ui->textEdit_2->setText("yea");
}

Button for test

void MainWindow::on_pushButton_2_clicked()
{
    QSqlQuery test;
    test.exec("SELECT idcriterion,name FROM criterion");
    //qDebug() << test.lastError().text() << "num " << test.lastError().number();
    ui->textEdit->setText(test.lastError().text());
    while (test.next())
    {
    QString id = test.value(0).toString();
    QString name = test.value(1).toString();
    ui->textEdit->insertPlainText(id+" "+name+"
");
    }
}

Its working perfect on Desktop but Android build take an exept on second button:

no such table:criterion Unable to execute statement

though database connect "yea"

Android: SDK: 4.0 NDK: 21.3.6528147 JDK: 1.8 SDK tools: 29 Emulator Android 10

in .pro file

android: {
    deployment.path = /assets
    deployment.files = test.db
    INSTALLS += deployment
}
question from:https://stackoverflow.com/questions/65952904/qt-android-sqlite-no-such-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Its problem on incorrect database path for Android.

If initialized directly "test.db", SQLite driver creates a new empty db file with this name, cos cant find it on android directory.

Right variant for 1st button:

QString dbFile = "test.db";
QString emptyFile = "assets:/" + dbFile;
QFile dfile( dbFile ), originalFile( emptyFile );
if ( !dfile.exists() )
{
    originalFile.copy("./test.db");
    QFile::setPermissions("./test.db", QFile::WriteOwner | QFile::ReadOwner );
}
if( QFile::exists( dbFile ) )
{
    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName( dbFile );
    if(!db.open())
        ui->textEdit_2->setText(db.lastError().text());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...