How to connect client server system with SQlite - c++

In client server program I want the message received from client save in "SQLite" database.I mean as code below shows "IPAddress, message and date" from server save in database.How should i connect these together? Thanks in advance.
QString IPAddress= m_client->peerAddress().toString();
qDebug()<<"IP Address:"<< IPAddress;
}
void myserver::readSocket()
{
QByteArray message = m_client->readAll();
qDebug() <<" Data in: " << message;
QDate date=QDate::currentDate() ;
qDebug() << date;
m_client->write(message);
}
void MainWindow::createdata()
{
QSqlQuery query;
query.exec("DROP TABLE messages");
query.exec("CREATE TABLE messages("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"IPAddress VARCHAR(20),"
"date VARCHAR(10),"
"message VARCHAR(30))");
query.prepare("INSERT INTO messages(IPAddress, date, message) values(?,?,?)");

Related

Qt & SqlLite inset data to database

I'm doing Qt application. I am trying save data in database. I have got problem because I have got connection with sqlite3, but when i want insert data QT says that QSqlQuery::prepare: database not open.
void DodajKontakt::on_btn_add_clicked()
{
QSqlDatabase db_kon = QSqlDatabase::addDatabase("QSQLITE");
db_kon.setDatabaseName("C:/Users/Lukasz/Desktop/qt master/organizator/baza_kontakty.db");
QSqlQuery query;
query.prepare( "CREATE TABLE kontakty(ids INTEGER PRIMARY KEY, name TEXT, surname TEXT, company TEXT, email TEXT, phone TEXT");
if(!db_kon.open())
{
qDebug() << "error:" << db_kon.lastError().text();
}
else
qDebug() << "Succsess";
if(ui->lineEdit_name->text().isEmpty() && ui->lineEdit_surname->text().isEmpty()
&& ui->lineEdit_email->text().isEmpty() && ui->lineEdit_phone->text().isEmpty()
&& ui->lineEdit_company->text().isEmpty())
{
QMessageBox::critical(this, tr("Error"), tr("Uzupełnij wszystkie pola!"));
}
else
{
QString name, surname, company, email, phone;
name = ui ->lineEdit_name->text();
surname = ui ->lineEdit_surname->text();
company = ui ->lineEdit_company->text();
email = ui ->lineEdit_email->text();
phone = ui ->lineEdit_phone->text();
query.prepare("INSERT INTO kontakty(name,surname,company.email.phone) VALUES('"+name+"','"+surname+"','"+company+"','"+email+"','"+phone+"')");
if(query.exec())
QMessageBox::information(this, tr("Sukces"),tr("Dodano nowy kontakt"));
else
QMessageBox::information(this, tr("Error"),tr("Nie udalo sie dodac nowego kontaktu"));
}
}
It is results.
QSqlQuery::prepare: database not open
Succsess
Can someone help me?
Your main error is that you are trying to create the table before opening the database, that's why you get that error.
Another error that is repetitive is that even when a problem happens your logic will still want to insert data, what you should do is print an error message and return.
You also have errors in the query, for example in the creation of the table you need to close with a parenthesis.
And finally do not build the query directly if you are going to use data provided by the user since your system will be prone to SQL Injection, it is appropriate to use the bind-value.
QSqlDatabase db_kon = QSqlDatabase::addDatabase("QSQLITE");
db_kon.setDatabaseName("C:/Users/Lukasz/Desktop/qt master/organizator/baza_kontakty.db");
if(!db_kon.open()){
qDebug() << "error:" << db_kon.lastError().text();
return;
}
qDebug() << "Success";
QSqlQuery query;
query.prepare( "CREATE TABLE kontakty(ids INTEGER PRIMARY KEY, name TEXT, surname TEXT, company TEXT, email TEXT, phone TEXT)");
if(!query.exec()){
qDebug()<<"error:" << query.lastError().text();
return;
}
QString name = ui->lineEdit_name->text();
QString surname = ui->lineEdit_surname->text();
QString company = ui->lineEdit_company->text();
QString email = ui->lineEdit_email->text();
QString phone = ui->lineEdit_phone->text();
if(name.isEmpty() &&
surname.isEmpty() &&
email.isEmpty() &&
phone.isEmpty() &&
company.isEmpty())
{
QMessageBox::critical(this, tr("Error"), tr("Complete all fields!"));
return;
}
query.prepare("INSERT INTO kontakty(name, surname, company, email, phone) VALUES(?, ?, ?, ?, ?)");
query.addBindValue(name);
query.addBindValue(surname);
query.addBindValue(company);
query.addBindValue(email);
query.addBindValue(phone);
if(query.exec())
QMessageBox::information(this, tr("Success"),tr(" A new contact has been added"));
else
QMessageBox::information(this, tr("Error"),tr("It was not possible to add a new contact"));

SQLite CREATE query in QT

dataBase = QSqlDatabase::addDatabase("QSQLITE");
dataBase.setDatabaseName("login_password.sqlite");
QSqlQuery authQuery;
if(!dataBase.open())
{
qDebug() << dataBase.lastError().text();
}
QString create("CREATE TABLE BASE(LOGIN VARCHAR(15) PRIMARY KEY NOT NULL, "
"PASSWRD TEXT(50) NOT NULL, RIGHTS INT NOT NULL);");
bool state = authQuery.exec(create);
if(!state) qDebug() << "Не удалось создать таблицу!";
What's wrong with query and is it possible to make text PRIMARY KEY?
From the docs:
Warning: You must load the SQL driver and open the connection before a
QSqlQuery is created. Also, the connection must remain open while the
query exists; otherwise, the behavior of QSqlQuery is undefined.
In your question, you are creating the QSqlQuery before opening the database, you have to move the authQuery declaration statement after the dataBase.open() call, like this:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("login_password.sqlite");
if (!db.open())
qDebug() << "error opening database: " << dataBase.lastError().text();
QSqlQuery authQuery;
QString create("CREATE TABLE BASE(LOGIN VARCHAR(15) PRIMARY KEY NOT NULL, "
"PASSWRD TEXT(50) NOT NULL, RIGHTS INT NOT NULL);");
if(!authQuery.exec(create)){
qDebug() << "error executing statement: " << authQuery.lastError().databaseText();
}

Qt Sqlite table column appears to be gone

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":temp:");
if (!db.open()) {
qDebug() << "Database open error." << db.lastError();
return;
}
QSqlQuery query(db);
query.prepare("create table if not exists dew (id int, title varchar(255) not null)");
if (!query.exec()) {
qDebug() << "Query exec error. " << query.lastError();
return;
}
qDebug() << "Insert query exec OK";
if (!query.exec("insert into dew(id, title) values (1, 'hello')")) qDebug() << query.lastError();
Shows the output as
Insert query exec OK
QSqlError(1, "Unable to execute statement", "table dew has no column named id")
Insertion finished.
Table creation seems to be OK. But where is id field? I'm confused with this code. I test query.record().contains("id"); and it is false
":temp:" is not a valid name for a temporary database, this creates a regular database on disk which stays after the database connection is closed.
To create a temporary or an in-memory sqlite database, that won't be saved to a file, you need to pass respectively an empty string (*) or the special string ":memory:" as the database name.
http://www.sqlite.org/inmemorydb.html
Qt doesn't allow an empty QString as the database name, but a QString starting with a '\0' should work: db.setDatabaseName(QChar(0));

QSqlQuery not positioned on a valid record

I'm trying select a field of my date base, the code is:
if (db.db().isOpen())
{
qDebug() << "OK";
QSqlQuery query("SELECT state FROM jobs WHERE jobId = '553'", db.db());
qDebug() << query.value(0).toString();
}
else
qDebug() << "No ok";
The query is correct because when I do qDebug() << query.size;, it returns 1.
but with qDebug() << query.value(0).toString();, it returns:
OK
QSqlQuery::value: not positioned on a valid record
""
How can I fix it?
You should call query.first() before you can access returned data. additionally if your query returns more than one row, you should iterate via query.next().

Problem with SQLite & Qt

This is the code which has problem:
QMessageBox::information(this, "Connexion Open", "Connexion BD Ok!");
QSqlQuery req;
req.exec("SELECT * FROM reservation");
while(req.next()) {
float id = req.value(0).toFloat();
text2->setText(" "+QString::number(id)+" " );
The message "Connexion BD Ok!" appears perfectly.
How can I retrieve the result of the DB knowing that the DBMS(SGBD) is SQLite?
Thank You
It looks like you are already retrieving the id, so I'm guessing that your question is how you connect to a sqlite database in the first place with Qt. You typically specify the database when you are connecting. Something like:
QSqlDatabase db = QSqlDatabase::addDatabase(ntr("QSQLITE"));
QFileInfo dbPath(pathToDb, dbFileName);
db.setDatabaseName(dbPath.absoluteFilePath());
if (!db.open()) {
qDebug() << ntr("Could not open database:") << db.databaseName();
}
if (db.isOpenError()) {
QSqlError err = db.lastError();
qDebug() << ntr("Last error:") << err.text();
}