How to test whether the sql command executed or not ?

Posted by Akiii under C# on 3/22/2011 | Points: 10 | Views : 5267 | Status : [Member] | Replies : 4
Hi,
I have used the following code:-

string sql = "insert into reg_table(name, gender, phone, country) values('" + name + "', '" + gender + "', " + phone + ", '" + country + "')";
SqlCommand MyCmd = new SqlCommand(sql, conn);


Now, i want to test if the data is inserted in the database or not. If the data is inserted then it will show me a messagebox and say "data inserted" or "not inserted"...??
can anybody help?

Thanks and Regards
Akiii




Responses

Posted by: SheoNarayan on: 3/22/2011 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
First of all, this is not good way of inserting the data into the database as it exposes your script to SQL Injection. Always use parameterized SQL statement.

To know whether the record has been inserted, you should execute the NonQuery statement to a variable like below.

var resultSet = MyCmd.ExecuteNonQuery();

if (!resultSet.Equals(0))
{
// result inserted successfully
}


Read the insert method in this article - http://www.dotnetfunda.com/articles/article71.aspx

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 3/22/2011 [Member] Bronze | Points: 25

Up
0
Down
Thank you sir for ur valuable feedback but what is sql attack ??

i am studying the articles of that link you provided.....

Thanks and Regards
Akiii

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: SheoNarayan on: 3/23/2011 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Vuyiswa had written a small article on SQL Injection (also sometimes called SQL Attack), read this http://www.dotnetfunda.com/articles/article295.aspx.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 3/23/2011 [Member] Bronze | Points: 25

Up
0
Down
@SheoNarayan.......Sir i have followed the SQL injection article and modified my code by using stored procedure and its working fine....

Thank you very much for your help....
Akiii

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response