I have a table in my SQL Server database:
DOCUMENT(DOC_NUM,DOC_NAME,...)
{
DOC_NUM: nvarchar(50);
...
}
And table DOC_NUM has one row with DOC_NUM= DD121;
And in webform I execute a query:
string docnum= "DD121";
string sql= "select * from DOCUMENT where DOC_NUM="+docnum;
Datatable doc= ....EXECUTEQUERYSQL(sql);
int count= doc.Rows.Count;
It causes an error:
An unhandled exception occurred during the execution of the current web request.
on the line of code:
int count= doc.Rows.Count;
But when I change it to:
string sql= "select * from DOCUMENT where DOC_NUM= 'DD121'";
Datatable doc= ....EXECUTEQUERYSQL(sql);
int count= doc.Rows.Count;
It worked fine!
I don't really know why?
When you use this string concatenation, your query will be DOC_NUM= DD121 instead of DOC_NUM= 'DD121' which is wrong.
And this kinf of string concatenations are open for SQL Injection attacks.
Use parameterized queries instead;
string sql= "select * from DOCUMENT where DOC_NUM = @docnum";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@docnum", docnum);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With