To fix the SQL Injection vulnerability:
private void saveCart(int sno, String BkName, String BkLanguage, String BkStd, String BkQty,String BkPrice, String TotalPrice)
{
const string mycon = "Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=NoveltySystem;Integrated Security=True;Pooling=False";
const string query = "insert into saveCart (sno, BkName, BkLanguage, BkStd, BkQty, BkPrice, TotalPrice) values (@sno, @BkName, @BkLanguage, @BkStd, @BkQty, @BkPrice, @TotalPrice)";
using (SqlConnection con = new SqlConnection(mycon))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@sno", sno);
cmd.Parameters.AddWithValue("@BkName", BkName);
cmd.Parameters.AddWithValue("@BkLanguage", BkLanguage);
cmd.Parameters.AddWithValue("@BkStd", BkStd);
cmd.Parameters.AddWithValue("@BkQty", BkQty);
cmd.Parameters.AddWithValue("@BkPrice", BkPrice);
cmd.Parameters.AddWithValue("@TotalPrice", TotalPrice);
con.Open();
cmd.ExecuteNonQuery();
}
}
It then becomes obvious that you're specifying more values in the
VALUES
clause than columns in the
INSERT INTO
clause - as already mentioned in Solution #1.
You also need to wrap your connection and command objects in
using
blocks, so that they are cleaned up properly. With your current code, you will eventually run out of connections, and start getting errors when you try to open a new connection.
using statement - C# Reference | Microsoft Docs[
^]
You should also look at loading your connection string from your application's configuration file, rather than hard-coding it throughout your code.
Connection Strings and Configuration Files | Microsoft Docs[
^]