PDA

View Full Version : how to add data Into database using a dialog



akilimob
13th April 2012, 19:49
hello everyone i am currently implementing a gui app, the problem is i cant quite figure out how to insert data into a database using values from a dialog NOTE i want the user to enter the values in the dialog and then those values are inserted into the database e.g, can anyone please post me a snippet of how to do this. please i will appreciate very much

qlands
14th April 2012, 15:15
Hi,

I'm assuming you are sub-classing a QDialog its has some widgets (for example lineEdits) and the insertion happens once the user close the dialog.

Lets say for example that mydialog has two lines edits: Code (lineEdit) and Name (lineEdit_2)

declare two private members in mydialog:

in the .h


...
private:
QString m_code;
QString m_name


declare two public functions to get the name and code:

in the .h


public:
QString getCode(){return m_code;}
QString getName(){return m_name;}


I guessing you have a "OK" or "Close" button, so move the data from the edits to the private members when closing

in the .cpp


m_code = ui->lineEdit->text();
m_name = ui->lineEdit_2->text();


Now another window is the one calling the dialog right?



//Creates the dialog, execute it and wait until close
mydialog mydlg;
mydlg.exec();

//Insert the data. I'm old fashion so I prefer to write SQL code and the execute it....but QT has many classes to handle inserts in a more automatic way.
QString sql;
QSqlQuery qry(mydb); //mydb has to be created previously. Is a QSQLDatabase... See help if you don't know how to open and database

sql = "INSERT INTO mytable (code,name) VALUES ('" + mydlg.getCode() + "','" + mydlg.getName() + "')"; //Creates the sql insert

qry.exec(sql); //Executes the insert



And that's it.

Good luck.

ChrisW67
16th April 2012, 02:13
sql = "INSERT INTO mytable (code,name) VALUES ('" + mydlg.getCode() + "','" + mydlg.getName() + "')"; //Creates the sql insert


It also creates reliability and security issues if you get into the habit of building queries this way. If one of the user's name entries was "Miles O'Brien (Star Trek)" (without the enclosing quotes) the INSERT will fail. If the INSERT was a DELETE the consequences could be dire:


sql = "DELETE FROM mytable WHERE code = '" + mydlg.getCode() +"'";

seems safe enough until someone exploits the weakness by typing "x' OR code is not null; -- " in as the code, making the query:


DELETE FROM mytable WHERE code = 'x' OR code is not null;-- '

and trashes much data (on most RDMS systems). Might not matter on your single-user desktop app, but it matters greatly in the broader world.

QSqlQuery provides Approaches to Binding Values that ensure user input is safely handled: please use them.