Problems with QSQL
-
I am trying to learn QSQL and I am having some trouble. I want to create an SQLite database, since, as far as I've read, it requires no further setting up. I want to create a table called "employees" with Firstname (string), Lastname (string) and Department (int) values; after that I want to add some values to the database and do some more processing. I am posting the code below, I have some errors in it. Help is appreciated
@ QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "EmbeddedDB");
db.setDatabaseName("AWESOME");
QSqlQuery query;
QSqlRecord record = query.record();query.exec("create table employees " "firstname varchar(20), " "lastname varchar(30), " "department integer"); //add first person query.prepare("INSERT INTO employees (lastname, firstname, department)" "VALUES(:lastname, :firstname, :department)"); query.bindValue("lastname", "Hasse"); query.bindValue("firstname", "Peter"); query.bindValue("department", 3); // add second person query.prepare("INSERT INTO employees (lastname, firstname, department)" "VALUES(:lastname, :firstname, :department)"); query.bindValue(":lastname", "Dzhe"); query.bindValue(":firstname", "Viktor"); query.bindValue(":department", 2); query.exec(); //add final person query.prepare("INSERT INTO employees (lastname, firstname, department)" "VALUES(:lastname, :firstname , :department)"); query.bindValue(":lastname", "Andrew"); query.bindValue(":firstname", "Pender"); query.bindValue(":department", 1); query.exec(); query.prepare("SELECT firstname, lastname FROM employees"); QString firstname = query.value(record.indexOf("firstname")).toString(); cout << firstname << endl;@
-
Line 1 creates a named connection to a database.
Line 3 creates a query related to the default (unnamed) database connection, which is not the one named "EmbeddedDB".Either pass db to the QSqlQuery constructor so it is using the named connection, or don't name the connection (it becomes the default).
Line 4 will give you an empty record, that you later rely on unchanged. Rethink how you access the SELECT data
QSqlQuery::lastError() is your friend