2 Attachment(s)
How to check Primary key is Exists in Table ?
I have a Database with Table SinhVien ( MSSV, HoTen, Lop_MaLop ),
Attachment 7199
I created QT C++ project with Buttons: Add, Edit, Del and connect to my Database (QMySQL). When I enter a value to MSSV and press Edit Button, will be edit information of HoTen, Lop_MaLop look like code :
Attachment 7200
QSqlQuery *qry=new QSqlQuery();
qry->prepare(
"UPDATE SinhVien SET HoTen = '" + ui.txtTenSinhVien->text()
+ "', Lop_MaLop = " + ui.txtLop->text() + " where MSSV = "
+ ui.txtMaSV->text() + "");
qry->exec();
It's work but we can not know the value entered on MSSV is Exists or Not Exists in Database (Table MSSV ), How to check ? I try this code but not work :
QSqlQuery *qry=new QSqlQuery();
if("exists(select MSSV from SinhVien where MSSV = )" + ui.txtMaSV->text())
{
qry->prepare(
"UPDATE SinhVien SET HoTen = '" + ui.txtTenSinhVien->text()
+ "', Lop_MaLop = " + ui.txtLop->text() + " where MSSV = "
+ ui.txtMaSV->text() + "");
qry->exec();
QMessageBox::information(this, QString::fromUtf8("Yeah !."),
QString::fromUtf8("Edit successful !"));
ShowData();
}
else
{
//QMessageBox::information(this, QString::fromUtf8("Warning !."),
//QString::fromUtf8("MSSV Not Exists in Database!"));
return;
}
Thanks for Help !
Re: How to check Primary key is Exists in Table ?
You need to build an SQL query with that exists clause in the where part of the query. execute it, and look at the result.
You should also avoid building queries by joining query fragments as strings. This is hard to read and maintain, is easy to break, and opens up security issues. Use named parameters and the bindValue() function. See Approaches to Binding Values
Re: How to check Primary key is Exists in Table ?
Thanks ChrisW67,
I read bindValue() function and will be apply to code.
see you again :D
Re: How to check Primary key is Exists in Table ?
I finished my code, share to another Beginners:
Code:
checkexists->prepare("select MaDaiLy from DaiLy where MaDaiLy = " + ui.txtMaDL->text());
checkexists->exec();
if((checkexists->last())==true)
{
//exists
}
else
{
//not exists
// do something.
}
Re: How to check Primary key is Exists in Table ?
This is not working because You are executing query like this :
Code:
select MaDaiLy from DaiLy where MaDaiLy = blablabla
and of course You got an error from SQL engine because You don't have column 'blablabla' in table DaiLy. You should do this like :
Code:
checkexists->prepare("select MaDaiLy from DaiLy where MaDaiLy = ?");
checkexists->bindValue(0, ui.txtMaDL->text());