I tried to create a SQLite database with Qt and and I did!! I called my db “prova_db” and it contains the following table:
marker_db
id site (columns)
0 www.google.it
1 www.youtube.it
2 www.facebook.it
Then, I tried to query my prova_db. Here is code:
int main () {
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("prova_db");
if (!db.open()) { printf("DB doesn't exist\n");}
else {
QSqlQuery query1;
query1.exec( "SELECT site FROM marker_db WHERE id = 1");
int i = query1.numRowsAffected();
printf("result row: %d\n", i);
while(query1.next()){
QString str = query1.value(0).toString();
printf("result: %s\n", str);
}
}
db.close();
return 0;
}
The result is:
result row : 0
result : (strange char)
instead the result should be:
result row: 1
result : www.youtube.it
where am I doing wrong??
Thank you!
I think you have the wrong expectation: the result of
numRowsAffected()tells you how many rows have been altered by the query. Your query does not alter anything, so the result should be either0or undefined. Thus, you shouldn’t expect the first output to berisultato riga: 1. Use thesize()method instead to find out how many rows have matched yourSELECTquery.The second problem is that you are passing a
QStringobject toprintf(), which expects a pointer to a null-terminated array ofcharvalues instead (when you use the%sformat specifier). You need to convert theQStringobject into a pointer to a C array of characters.