My english is not very good but i’ll try to describe my problem.
So, i have primitive code:
base = QSqlDatabase::addDatabase("QODBC");
QSettings sets("FlowModel","Settings");
currentBase = sets.value("currentBase").toString();
base.setHostName("localhost");
base.setDatabaseName(QString("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=%1").arg(currentBase));
if(base.open())
QMessageBox::information(0,"Все отлично!","База данных открыта","Ок");
else
QMessageBox::information(0,"Все не ахти!",base.lastError().text(),"Ок");
QSqlQuery queryMaterials("SELECT * FROM Материал",base);
int fieldNo = queryMaterials.record().indexOf("Название");
int i = 0;
while (queryMaterials.next()) {
comboBox->insertItem(i++,queryMaterials.value(fieldNo).toString());
}
queryMaterials.clear();
It works correctly and combo box takes all materials from Database;
But next is going this code:
QSqlQuery queryInfo("SELECT * FROM Свойства_материала WHERE Название='Вода'",base);
fieldNo = queryInfo.record().indexOf("P");
pLine->setText(queryInfo.value(fieldNo).toString());
And it didn’t work! Query returns an empty string (”“), but must be a number. I test this SQL-query in Access and there it works correct. Please help to understand what a problem i have.
Thank you.
P.S. I’m tried to use QSqlQuery::lastError().text() method, but it report me nothing.
I can’t understand what is that… Because this table can be opened by this code:
QSqlDatabase accessBase = QSqlDatabase::addDatabase("QODBC");
accessBase.setHostName("localhost");
accessBase.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=D:/ИТ.mdb");
if(accessBase.open())
QMessageBox::information(0,"Все отлично!","База данных открыта","Ок");
else
QMessageBox::information(0,"Все не ахти!",accessBase.lastError().text(),"Ок");
QTableView tableGhost;
QSqlTableModel tableDB;
QString whtpn = QInputDialog::getText(0, "Какую таблицу открыть?",
"Какую таблицу открыть?");
tableDB.setTable(whtpn);
tableDB.select();
tableDB.setEditStrategy(QSqlTableModel::OnFieldChange);
tableGhost.setModel(&tableDB);
tableGhost.show();
And all ok. But by query no(
Problem has been solved.
Before line
pLine->setText(queryInfo.value(fieldNo).toString());
Had to use method QSqlQuery::next();
Related
I have spent ages searching for an answer to this, but i can't quite get my head around it.
Basically.I have a sqlite db on a sd card connected to a esp32. SQLite works perfectly and will return when using the standard sample code. For example:
rc = db_exec(db2, "Select * from domain_rank where domain between 'google.com' and 'google.com.z'");
if (rc != SQLITE_OK) {
sqlite3_close(db1);
sqlite3_close(db2);
return;
}`
this looks at a "db_exec" function in the sketch then passes it to a "callback" function. Is there a way to do without this? All I want to do is count the number of records in a select statement.
Thanks
Andrew
Ok I think I may have found a solution
Putting it here just in case anyone else is interested.
String sql = "Select count(*) from surnames where name = 'MICHELLE'";
rc = sqlite3_prepare_v2(db1, sql.c_str(), 1000, &res, &tail);
if (rc != SQLITE_OK) {
String resp = "Failed to fetch data: ";
Serial.println(resp.c_str());
return;
}
while (sqlite3_step(res) == SQLITE_ROW) {
rec_count = sqlite3_column_int(res, 0);
}
Serial.println(rec_count);
can't quite get my head around what the while loop is doing counting the cells, i thought the sql count* query would just return an int value I could use directly. So I'm still a little confused.
Comments would be welcomed! If anyone has any better ideas?
Thanks
Andrew
I am making a library management software using Qt and Sqlite3.
constructor:
db = QSqlDatabase :: addDatabase("QSQLITE");
model = new QSqlTableModel(this, db);
db.setDatabaseName(":/lib/libre coupe.db");
db.setHostName("Libre Coupe");
if(db.open())
{
QSqlQuery query(db);
if (! query.exec("CREATE TABLE IF NOT EXISTS books (NAME VARCHAR(100) NOT NULL, AUTHOR VARCHAR(100) NOT NULL, UID VARCHAR(100) NOT NULL) "))
{
QMessageBox::information(this, "title", "Unable to use Sqlite");
}
if(query.lastError().text() != " ")
QMessageBox::critical(this, "Oops", query.lastError().text());
model->setTable("books");
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("Name") );
model->setHeaderData(1, Qt::Horizontal, tr("Author") );
model->setHeaderData(2, Qt::Horizontal, tr("Uid") );
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
if(!query.exec("SELECT * FROM books;"))
QMessageBox::critical(this, "Oops", query.lastError().text());
int i = 0;
while(query.next())
{
model->setData(model->index(i, 0), query.value(query.record().indexOf("NAME")));
model->setData(model->index(i, 1), query.value(query.record().indexOf("AUTHOR")));
model->setData(model->index(i, 2), query.value(query.record().indexOf("UID")));
++i;
}
}
else
QMessageBox::critical(this, "Oops!", "Could not open the database");\
I faced a problem that the database was not created automatically. So, i created it manually and added it to my resource so that it exists on every computer which uses my application.
I ran my app and went to the directory containing "libre coupe.db". There using the terminal, i found out that no table was created. I see no error message. My other functions like save don't work too while the same commands typed directly into Sqlite using terminal works as expected.
I even used the debugger and found that the program does enter the if condition i.e. the database opens successfully.
I used the following command to check if the table existed:
sqlite3 "libre coupe.db"
.tables
First line:
db.setDatabaseName(":/lib/libre coupe.db");
the starting ":" means you are trying to access an embedded binary resource using Qt's resource system.
However, SQLite databases cannot be stored in the Qt resource system. If your database is instead located at /lib/libre coupe.db, you should remove the colon at the beginning.
So I am developing this add-on using the MDN's Add-on Builder and need to connect with the SQLite Database. The connection gets created fine and insertion is fine as long as I am inserting values without binding parameters(that is, through executeSimpleSQL()). As soon as I use the createStatement() method to INSERT values, it does not work. Here's what I have done so far.
let file = FileUtils.getFile("Desk", ["my_db_file_name.sqlite"]);
let mDBConn = Services.storage.openDatabase(file);
mDBConn.executeSimpleSQL("CREATE TEMP TABLE IF NOT EXISTS element (rating VARCHAR(50))");
let stmt = mDBConn.createStatement("INSERT INTO element (rating) VALUES(:value)");
stmt.params.value = 13;
//mDBConn.executeSimpleSQL("INSERT INTO element (rating) VALUES(13)");
var statement = mDBConn.createStatement("SELECT * FROM element WHERE rating = :rat");
statement.params.rat = 13;
try {
while (statement.step()) {
let value = statement.row.rating;
console.log(value);
}
}
finally {
statement.reset();
}
Note that the SELECT statement with the bound parameters works fine, it's just the INSERT statement that's problematic.
Any ideas?
You forgot to call execute().
I have saved an image in sqlite and i am trying to retrieve it and displaying it in a QLabel using this code.
connect(ui.tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
this, SLOT(getImage(QModelIndex,QModelIndex)));
void smith::getImage()
{
.......
QModelIndex index = ui.tableView->currentIndex();
QString sqlQuery = QString("SELECT image FROM %1 WHERE id=:id").arg(tableName);
query.prepare(sqlQuery);
QSqlRecord recordz = tableModel->record(index.row());
query.bindValue(":id", recordz.value("id").toInt());
query.exec();
tableModel->select();
QByteArray array = query.value(0).toByteArray();
QBuffer buffer(&array);
buffer.open( QIODevice::ReadOnly );
QImageReader reader(&buffer, "PNG");
QImage image = reader.read();
if( image.isNull() )
{
QMessageBox::about(this, tr("Image Is Null"),
tr("<h2>Image Error</h2>"
"<p>Copyright © 2011."
"<p>Message Box To Check For "
" Errors "
));
}
ui.imageLabel->setPixmap( QPixmap::fromImage(image));
}
The project compiles without any errors but the image won't show.
I'd suggest adding some error-checking to your code, to narrow down where the error occurs.
For example, the documentation for QImageReader::read() says that if the image can't be read, the resultant image is null, and it tells you how to find out what the error was.
So after your call to reader.read(), check image.isNull().
And earlier on, check array.size() to make sure that you really got a value back from the database.
And the check the result returned by buffer.open( QIODevice::ReadOnly ) - the docs say it will return false if the call failed.
I decided to test sqlite db for my Qt application.
I have created the sqlite db file with the proper statements (create table etc. and Inserted some rows of data).
My problem is that when I execute a select statement I don't get any records.
This is the code I use:
qq.sprintf("SELECT * from descriptors WHERE descriptors.id=%d ",idx);
query.exec(qq);
if( query.isSelect() ){
while (query.next()){
int fff = query.value(0).toInt();
}}
The problem is that I never get inside the while loop. query.next() doesn't seem to work.
any hints?
thanks in advance,
Thodoris
p.s. I forgot to write my configuration so: Qt 4.7.3, windows 7, visual studio 2008
Other than the mistake hexa posted, query.isSelect() will always return true even if the query failed. You need to check the result of exec():
QSqlQuery query;
query.prepare( "SELECT * FROM descriptors WHERE id = ?" );
query.bindValue( 0, idx ); // assuming idx is an integer/long/QVariant value
if( !query.exec() )
{
// Error Handling, check query.lastError(), probably return
}
// Note: if you don't return in case of an error, put this into the else{} part
while( query.next() )
{
int fff = query.value( 0 ).toInt();
}
In my case, backward iteration over QSqlQueries worked. I think this could be a bug somewhere in the QSQLite Driver implementation.
QSqlQuery q = db.exec("SELECT * FROM Table");
if (q.last()) {
do {
// Do something with row...
} while (q.previous());
}