Hi,
I'm developing a C++ script to update postgresql database records. The
user interacts with the script via an html form. That is, the user is
presented with the data from a particular record in an html form and
asked to update any number of fields in that record.
To perform a multiple column update in postgres one does:
UPDATE tablename
SET column1 = 'blahblah',
column2 = 'moreblahblah',
column3 = 1234
WHERE id = 555;
Here's an excerpt from the script:
//sql statement
string sql;
sql = "UPDATE product SET ";
if (param["new_catid"] != param["old_catid"])
{
sql += "catid = " + param["new_catid"] + ",";
}
else if (param["new_catname"] != param["old_catname"])
{
sql += "prodname = '" + param["new_catname"] + "',";
}
else if (param["new_unitcnt"] != param["old_unitcnt"])
{
sql += "unitcnt = '" + param["new_unitcnt"] + "',";
}
else if (param["new_wprice"] != param["old_wprice"])
{
sql += "wprice = " + param["new_wprice"];
}
sql += "WHERE prodid = '" + param["prodid"] + "'";
int res = conn.Exec (sql.c_str()); //sql exec
Now the problem occurs when a user only wants to update certain columns,
which creates a syntax problem due to the comma (","). In other words
you cannot end a multiple column UPDATE statement with a comma followed by:
WHERE prodid = 'xyz';
Now I could probably solve this problem by building separate UPDATE
statements as such:
if (param["new_catid"] != param["old_catid"])
{
sql = "UPDATE product SET ";
sql += "catid = " + param["new_catid"];
sql += "WHERE prodid = '" + param["prodid"] + "'";
int res = conn.Exec (sql.c_str()); //sql exec
}
else if (param["new_catname"] != param["old_catname"])
{
sql = "UPDATE product SET ";
sql += "prodname = '" + param["new_catname"] + "'";
sql += "WHERE prodid = '" + param["prodid"] + "'";
int res = conn.Exec (sql.c_str()); //sql exec
}
This necessitates calling the database each time the if statement is
true. Is there perhaps a more efficient way of doing this? I'm assuming
that the fewer times you call the database the faster the program will run.
Thanks,
Mark Tessier