Can't execute mysql querys with QT - c++

I'm trying to connect and execute a query with the QT framework, I can connect to the mysql db and I have tested the query and verified it works on the database. I think the mysql driver is correctly installed because I can connect and it doesn't throw any errors
void Login::on_loginButton_clicked()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("127.0.0.1");
db.setDatabaseName("TestBase");
db.setUserName("username");
db.setPassword("password");
if (!db.open()) {
QMessageBox::critical(0,"Database Error","Could not connect to the database, check your internet connection.");
}
QSqlQuery data("SELECT * FROM `TestBase`.`Users` WHERE `userName` = 'Afonso'");
//data.exec("SELECT * FROM `TestBase`.`Users` WHERE `userName` = 'Afonso'");
QMessageBox::information(NULL, "Query executed", "The query returned: " + data.exec());
}
I have also tried with
data.exec("insert query here");
data.next();
Nothing seems to work
I am trying to display the result of the query in a QMessageBox

QSqlQuery query(db);
query.prepare("SELECT * FROM `TestBase`.`Users` WHERE `userName` = :user_name");
query.bindValue(":user_name", "Afonso");
if (!query.exec())
{
qDebug() << query.lastError().text();
retrun;
}
while (query.next())
{
QVariant v = query.value(0);
}

I use pyqt but in general with a select query, I start to get data with
.first() rather than .exec() .exec_() in pyqt.
After that next() works just fine.

Related

I can't insert data into my sqlite3 database using qt 6

I have a test.db database on my project directory, which I'm trying to insert data into. The database is connected, but I can't seem to insert data in it. The query is not executed at all (it seems), since the qDebug shows "Bad".
QSqlDatabase connectDB(){
QSqlDatabase db= QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test.db");
return db;
}
void planner::on_dataSend_clicked()
{
QSqlDatabase datba = connectDB();
if (datba.open()){
qDebug()<< "DB Suc";
} else{
qDebug() << "DB Fail";
}
QString what = ui->addPlan->text();
QSqlQuery qry;
qry.prepare("insert into plan values :what");
qry.bindValue(":what",what);
if (qry.exec()){
qDebug()<< "Good";
qry.clear();
} else{
qDebug()<<"Bad";
qDebug()<<qry.lastError();
qry.clear();
}
datba.close();
ui->addPlan->clear();
}
I'm using DB Browser for SQLite, and this is the database
The error that QSqlError shows is parameter count mismatch here
On SQLITE table, there is a default column as a primary key called rowid, you need to spécify the column that you want to add like this:
qry.prepare("insert into plan (column_name) values (:what)");

How to deal: QSqlQuery::exec() returns false

I'm using Qt and sqlite3. The problem is:
QSqlQuery::exec() returns false.
I thought it is caused by QSqlDatabase::open() because it always returns true!
I found that actually does not matter what i set using QSqlDatabase::setDatabaseName(), it will return true, because sqlite will create non existing DB.
I used QFile::exist to test if DB exists. But everything is fine and QFile sees the db.
Code:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("temp_client_db.sl3");
QFile datebase("temp_client_db.sl3");
if (!datebase.exists() || !db.open())
{
QMessageBox::critical(this, "Error", "Database isn't connected.");
}
else
{
QSqlQuery query;
query.prepare("SELECT * FROM exist_ask");
if (!query.exec())
{
QMessageBox::critical(this, "Error", "\"SELECT exist_ask\" works badly.");
}
else
{
...
I just did not add the database to the build directory.

Connecting to Azure SQL Server with Qt on Linux

I am trying to connect to a Azure SQL Server database with Qt on Linux but I have not could make it. I tried some like this: Connection to SQL Server with qt but the connection is never opened.
My code is so simple:
QString connectionTemplate = "DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;";
QString connectionString = connectionTemplate.arg("tcp:my-database.database.windows.net,1433").arg("my-database");
for(int i = 0; i < QSqlDatabase::drivers().size(); i++) {
qDebug() << QSqlDatabase::drivers().at(i);
}
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName(connectionString);
db.setUserName("user#my-database");
db.setPassword("My password");
//db.setConnectOptions("Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;");
bool ok = false;
try {
ok = db.open();
} catch(QException ex) {
qDebug() << ex.what();
}
qDebug("%s=%d", "conexión abierta", ok);
QSqlQueryModel *model = new QSqlQueryModel;
QString query = "SELECT 1 AS test_col";
model->setQuery(query, db);
db.close();
I already have the QODB and QODBC3 drivers so I don't know why I am unable to make the connection.
Is some related to driver, Qt, Azure or similar?
This is what I am doing and it works perfect for me:
Note: connName is the connection name on which I am opening the database.
QString connectionString = "Driver={ODBC Driver 13 for SQL Server};"
"Server=tcp:xxx.database.windows.net,1433;"
"Database=ABC;"
"Uid=aaa#xxx;"
"Pwd=***;"
"Encrypt=yes;"
"TrustServerCertificate=no;"
"Connection Timeout=30;";
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", connName);
db.setDatabaseName(connectionString);
if (db.open())
{
return true;
}
else
{
QString error = db.lastError().text();
return false;
}

How to write Sqlite DataBase in Qt

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;
}
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>);");
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.

SQLite remove database error

I have widget which connects to database:
Widget::Widget(QWidget *parent)
{
QString databaseName = "name";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(databaseName);
db.setHostName("localhost");
if(!db.open())
qDebug()<<"ret error";
}
Now I want to delete database connection after widget close (currently I get warnings like: QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection is still in use...). I' ve read some topics and tried to evaluate some solution from them but none works for me. My code:
void Widget::closeEvent(QCloseEvent *e)
{
QSqlDatabase db = QSqlDatabase::database();
QString connection = db.connectionName();
db.close();
QSqlDatabase::removeDatabase(connection);
qDebug()<<"error: "<<db.lastError().text();
}
Error I get is: Driver not loaded Driver not loaded
What is the correct way to do this?
Edit:
another method:
void Widget::someMethod()
{
QSqlDatabase db = QSqlDatabase::database();
QSqlQuery query(db);
query.exec("some query");
}
Try giving a connection name parameter(2nd parameter) in addDatabase() , that should solve your problem.
Here is the modified code you could try:
Widget::Widget(QWidget *parent)
{
QString databaseName = "name";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "test_db_connection" );
db.setDatabaseName(databaseName);
db.setHostName("localhost");
if(!db.open())
qDebug()<<"ret error";
}
Here is a complete working code from my machine for sqlite database which you can use as reference:
local_db = QSqlDatabase::addDatabase("QSQLITE","localdb");
local_db.setDatabaseName("localdb.sqlite");
local_db_query = QSqlQuery(local_db);
local_db_query.prepare( "SELECT * FROM sample_table" );
local_db_query.exec();