0

I am using this code for creating SQlite Database in Qt. Now I have 2 questions: First how can I add new record in table , and second how can I check the table exist?

bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("SQLITE");
    db.setHostName("Server");
    db.setDatabaseName("Message.DB");
    if (!db.open()) {
        QMessageBox::critical(0, QObject::tr("Database Error"),
                db.lastError().text());
        return false;
}

2 Answers 2

3

Should be able to work:

QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName("Message.DB");
if(database.open() == false) {
    // ... <- Error handling
    return false;
}

QSqlQuery sqlQuery(database);
bool inserted = sqlQuery.exec("INSERT INTO my_table (col1, col2) VALUES (\'one\', \'two\')");
if(inserted == false) {
    // ... <- Error handling
}

Not sure how to check if table exists but to create a table if it does not already exist you can do:

bool created = sqlQuery.exec("CREATE TABLE IF NOT EXISTS my_table(<column info>);");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.