Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when request a nvarchar type in webform from SQL Server

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?

like image 579
vyclarks Avatar asked Dec 11 '25 05:12

vyclarks


1 Answers

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);
like image 82
Soner Gönül Avatar answered Dec 13 '25 19:12

Soner Gönül