I'm trying to insert data into a QtSql database, but I keep getting the error:
"Parameter count mismatch"
What could be what I'm doing wrong?
#include <QtSql>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << QSqlDatabase::drivers();
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("LOCALHOST");
db.setDatabaseName("people");
db.setUserName("root");
db.setPassword("");
if(db.open()) {
qDebug() << "Opened!";
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();
if( !query.exec() )
qDebug() << query.lastError().text();
else
qDebug( "Inserted!" );
db.close();
} else {
qDebug() << "Not opened";
}
}
You don't have a table named person in the database. You are trying to insert values into a table that does not exist.
I think that the error message is wrong. But anyway, I added a CREATE statement to your code, so that the table is created before the INSERT statement is executed:
#include <QtSql>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if(!db.open()){
qDebug() << "Not opened";
return 1;
}
qDebug() << "Opened!";
QSqlQuery query;
//CREATE the table before executing the INSERT statement
query.exec("CREATE TABLE person (id INTEGER, forename TEXT, surname TEXT);");
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
if( !query.exec() )
qDebug() << query.lastError().text();
else
qDebug( "Inserted!" );
return 0;
}
This prints Inserted! now. But if I comment out the CREATE statement line I get the same error in your question:
" Parameter count mismatch"
Related
I want to use QSqlTableModel since it seems easier to use. It does however not find my tables.
qDebug() << "connecting";
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(dbHostName);
db.setPort(dbPort);
db.setUserName(dbUserName);
db.setPassword(dbPassword);
// Connect to database sys to get some info to test (basic communication)
db.setDatabaseName("sys");
// Check if opened and if so get some data
if(db.open()){
qDebug() << "DB succesfully opened";
} else {
qDebug() << "DB failed to open";
return;
}
QSqlTableModel* runsSimulationViewModel = new QSqlTableModel();
runsSimulationViewModel->setTable("results.runs_simulation_view");
qDebug() << runsSimulationViewModel->lastError();
//ERROR: QSqlError("", "Unable to find table results.runs_simulation_view", "")
QSqlQuery anotherQuery;
anotherQuery.prepare("SELECT * FROM results.runs_simulation_view");
if(!anotherQuery.exec()) {
qDebug() << anotherQuery.lastError();
} else {
anotherQuery.next();
qDebug() << anotherQuery.value("simulation_id").toInt();
//Prints "3", which is the first value for this field in the table
}
QSqlQuery works, but QSqlTableView cannot find this (SQL) view (and also no tables).
What am I missing?
Juggling between receiving 2 different errors.
void summary::on_pushButton_saveSummary_clicked()
{
if(db.open())
{
query.exec("insert or replace into [PN:"+partNum+" CN:"+chargeNum+"](total, defects, rust) values(1, 2, 3)");
if (!query.exec())
{
qDebug() << query.lastError();
qDebug() << query.exec()<<endl;
}
}
else
{
qDebug() << db.lastError();
}
}
The above gives error: QSqlError("", "Unable to fetch row", "No query")
While:
void summary::on_pushButton_saveSummary_clicked()
{
if(db.open())
{
qDebug() << "db open";
int a = 3;
int b = 1;
int c = 3;
query.prepare("insert into [PN:"+partNum+" CN:"+chargeNum+"](total, defects, rust) values(:total, :defects, :rust)");
query.bindValue(":total", a);
query.bindValue(":defects", b);
query.bindValue(":rust", c);
if (!query.exec())
{
qDebug() << query.lastError();
qDebug() << query.exec()<<endl;
}
}
else
{
qDebug() << db.lastError();
}
}
Yields: QSqlError("", "Parameter count mismatch", "")
The Constructor has:
db.setDatabaseName("/home/igraves/Databases/testdb");
db.open();
QString partNum = "134345";
QString chargeNum = "3452";
query.prepare("create table if not exists [PN:"+partNum+" CN:"+chargeNum+"](total int, defects int, rust int)");
query.exec();
The table is being create, I can see it. So I am guessing syntax? Although it is as the Qt wiki writes it...
Edit:
Adding some .h stuff
QString partNum;
QString chargeNum;
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QSqlQuery query;
Answer: It was my QString variables being temporary, after the constructor was done, they went out of scope. Changed my .h
QString partNum = "124124";
QString chargeNum = "234234";
I see at least the following errors:
You do not set the database path.
Do not open the database when creating the table.
"134345" and "3452" are being assigned to temporary variables instead of class members
Considering the above, the following must be in the constructor:
partNum = "134345";
chargeNum = "3452";
db.setDatabaseName("/path/of/database.db");
if(db.open())
query.exec(QString("create table if not exists [PN:%1 CN:%2](total int, defects int, rust int)")
.arg(partNum)
.arg(chargeNum));
i am trying to search String in configuration file and if string match wants to delete key / value pair. i have getting qstringlist from file .
as far as my tried code is
int main(int argc, char *argv[])
{
QSettings* settings= new QSettings("/home/sidheshwar/Desktop/temp.txt", QSettings::IniFormat);
settings->beginGroup("Profiles");
const QStringList childKeys = settings->childKeys();
QStringList Keys;
QStringList values;
QString user="db-host";
QString tempUser;
foreach (const QString &childKey, childKeys)
{
Keys << childKey;
values << settings->value(childKey).toString();
}
for(int i=0;i< Keys.length();i++){
if(user == values.at(i)){
qDebug() << " keys" << Keys[i] << endl;
tempUser=Keys[i];
}
qDebug() << " tempUser" << tempUser << endl;
}
return 0;}
how can i use settings->remove(tempUser);
In the following example I show you an example of how to delete a data from the file that handles the configuration.
temp.ini before the execution.
[Profiles]
key1=db-host
key2=value2
key3=value3
main.cpp
#include <QCoreApplication>
#include <QSettings>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSettings* settings= new QSettings("temp.ini", QSettings::IniFormat);
settings->beginGroup("Profiles");
const QStringList childKeys = settings->childKeys();
QStringList Keys;
QStringList values;
QString user="db-host";
foreach (const QString &childKey, childKeys)
{
Keys << childKey;
values << settings->value(childKey).toString();
}
for(int i=0;i< Keys.length();i++){
if(user == values.at(i)){
qDebug() << " keys" << Keys[i];
settings->remove(Keys[i]);
}
qDebug() << Keys[i] << values.at(i);
}
return a.exec();
}
Output:
temp.ini after the execution
[Profiles]
key2=value2
key3=value3
I have a problem with Qt and sqlite. Until recently, I didn't have any problems creating tables, but now, whenever I try to create a table (using the exact same function) I get an error message:
QSqlError("1", "Unable to fetch row", "table selections already exists")
My query strings are as follows:
CREATE TABLE external_files (path VARCHAR (255) NOT NULL, used INTEGER (12) NOT NULL);
This is the same as before too.
The strange thing is though, all the tables are created without a problem, but I still get error messages.
If you have any ideas why this happens, I would appreciate it. :)
UPDATE: Minimal, complete, verifiable example:
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>
#include <QTextStream>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "CONN");
db.setDatabaseName("test.db");
if(!db.open()){
qDebug() << "Connection failed!";
}
QFile tableListFile(":/resources/sql/tables.sql");
if(tableListFile.open(QIODevice::ReadOnly))
{
QTextStream stream(&tableListFile);
while(!stream.atEnd())
{
QString queryString = stream.readLine();
qDebug() << "Query string: " << queryString;
QSqlQuery query(queryString, db);
if(!query.exec()){
qDebug() << "Query error: " << query.lastError();
}
}
}
db.close();
return a.exec();
}
Thanks in advance.
Ok, I managed to solve the problem.
The query was executed 2 times for each query string, and that caused the error messages.
To get to the solution, i edited my code like this:
QString queryString = stream.readLine();
qDebug() << "Query string: " << queryString;
QSqlQuery query;
if(!query.exec(queryString)){
qDebug() << "Query error: " << query.lastError();
}
I need some help in updating remote MySQL database using QT5.I am working on Linux Ubuntu 12.04.I want my app to connect to remote server and write some data to it.Any help will be greatly appreciated.
Here is an example:
#include <QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//use mysql driver
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
//set hostname
db.setHostName("localhost");
//set db name
db.setDatabaseName("test");
//set username and password
db.setUserName("user");
db.setPassword("pass");
//open db
bool ok = db.open();
qDebug() << "Db is open: " << ok;
//define a query
QSqlQuery query;
//set query
query.exec("SELECT * FROM `Persons`");
//get values from query
while (query.next()) {
QString LastName = query.value(1).toString();
QString FirstName = query.value(2).toString();
int age = query.value(3).toInt();
qDebug() << LastName << " " << FirstName << " " << age;
}
//close db
db.close();
return a.exec();
}