Reputation: 179
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;
}
Upvotes: 0
Views: 497
Reputation: 3950
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>);");
Upvotes: 3
Reputation: 1
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.
Upvotes: 0