'Adding data to SQLite through QT
I'm trying to make a registration form in Qt, I'm using SQLite database for this. When I run my program the compiler can open the database, however inserting info into this fails. I'm new to databases and will be very grateful if someone could help me to figure out what's the matter with it.
This is the part of my code about DB
database=QSqlDatabase::addDatabase("QSQLITE");
QString path = QFileDialog::getOpenFileName(0,"Open File","","DB files (*.sqlite) ;; All files (*)");
database.setDatabaseName(path);
if(database.open())
{
//creating a variable username
QString username;
//username equals to the input in the line editor
username= ui->usersname->text();
//creating a variable password
QString password ;
// password equals to the input in the line editor
password = ui->userspassword->text();
//creating a variable email
QString email;
//email equals to the input in the line editor
email = ui->usersemail->text();
//creating a variable phone number
QString phoneNumber ;
//phone number equals to the input in the line editor
phoneNumber= ui->usersphonenumber->text();
//running insert Query
QSqlQuery qry;
//put the info to the table created in the database
qry.prepare("INSERT INFO Users (Name, Password, Email, Phone)"
//select the values for inserting
"VALUES (:username, :password, :email, :phoneNumber)");
//binding values
qry.bindValue(":username", username);
qry.bindValue(":password", password);
qry.bindValue(":email", email);
qry.bindValue(":phoneNumber", phoneNumber);
//if adding info was successful
if(qry.exec())
{
//display a message box
QMessageBox::information(this, "Saved", "Your data was saved successfully, please log in");
}
//if adding info was not successful
else
{
QMessageBox::warning(this, "Failed", "Your data was not saved, please try again");
}
}
else
{
//display a warning message that the database was not connected
QMessageBox::warning(this,"Not Connected","The database is not connected");
}
Solution 1:[1]
C++ concatenates your query-string to:
INSERT INFO Users (Name, Password, Email, Phone)VALUES (:username, :password, :email, :phoneNumber)
The problem is that there is no space-character between "[...]Phone)" and "VALUES[...]".
This leads to the VALUES keyword cannot be parsed correctly.
To fix this, just place a space-character at the beginning of the second query-string-part like this:
//select the values for inserting
" VALUES (:username, :password, :email, :phoneNumber)");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dieselfahrverbot |
