Why does not the code for adding an entry in PostgreSQL work?
Unsolved
General and Desktop
-
Why does not the code for adding an entry in PostgreSQL work?
I'm using PostgreSQL version 9.5, Qt. I try to add an entry to the table, but the following code does not work for me:void MainWindow::SaveFiles() { Login conn; conn.connOpen(); QSqlQuery* queryAddNote = new QSqlQuery(conn.mydb); QString newDir = QString(QDir::currentPath()+"/Наблюдение_%1").arg(QString(QDate::currentDate().toString()).replace(" ","_")); QDir().mkdir(newDir); Progress->show(); Progress->setMinimum(0); for (int i=1;i<model->rowCount();i++) { Progress->setMaximum(model->rowCount()-1); if (model->index(i,0).data(Qt::DisplayRole).toBool()==true) { QFile::copy(model->index(i,1).data().toString(),newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName()); QString sqlQueryAddNote = QString("INSERT INTO public.\"DataObservationLog\" (data,path_data) VALUES (\"%1\",\"%2\")") .arg(QFileInfo(model->index(i,1).data().toString()).fileName()) .arg(newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName()); qDebug()<<sqlQueryAddNote; queryAddNote->prepare(sqlQueryAddNote); //queryAddNote->prepare("INSERT INTO DataObservationLog (data,path_data)" "VALUES (:data,:path_data)"); //queryAddNote->bindValue(":data", QFileInfo(model->index(i,1).data().toString()).fileName()); //queryAddNote->bindValue(":path_data", newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName()); qDebug()<<queryAddNote->lastError(); queryAddNote->exec(); Progress->setValue(i); } else { } } conn.connClose(); Progress->hide(); TableDisk->setModel(nullptr); }
Tried it like this:
```queryAddNote->prepare("INSERT INTO DataObservationLog (data,path_data)" "VALUES (:data,:path_data)"); queryAddNote->bindValue(":data", QFileInfo(model->index(i,1).data().toString()).fileName()); queryAddNote->bindValue(":path_data", newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName()); qDebug()<<queryAddNote->lastError(); queryAddNote->exec();
So :
QString sqlQueryAddNote = QString("INSERT INTO DataObservationLog (data,path_data) VALUES ('%1','%2')") .arg(QFileInfo(model->index(i,1).data().toString()).fileName()) .arg(newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName());
It connects to the database without errors and I connect as follows:
login.h #ifndef LOGIN_H #define LOGIN_H #include <QtSql> #include <QMessageBox> class Login { public: Login(); QSqlDatabase mydb; void connClose() { mydb.close(); mydb.removeDatabase(QSqlDatabase::defaultConnection); } bool connOpen() { mydb=QSqlDatabase::addDatabase("QPSQL"); mydb.setHostName("127.0.0.1"); mydb.setDatabaseName("ObservationLog"); mydb.setUserName("postgres"); mydb.setPassword("123456789"); if(!mydb.open()) { qDebug()<<("Не удачная попытка открыть базу"); return false; } else { qDebug()<<("База подключена..."); return true; } } }; #endif // LOGIN_H
-