0

In my program i need to get value from the database , so using a texbox so that client type anything and i can search from database.

My code is

 SqlCommand sqlcmd = sqlcon.CreateCommand();
 sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = " + textBox_cardNumber.Text;

the above is not my full code but here in my code i am using textbox_cardNumber ...

I want that in quotes ''

it should be like

Select distinct transactionName from dbo.tbl where terminalId = '0097'

So my question is how to get in quotes???

squillman
  • 13,363
  • 3
  • 41
  • 60
Sohail
  • 780
  • 3
  • 14
  • 27

6 Answers6

6

Use a parameterized query like this

SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl " + 
                     "where terminalId = @id";

sqlCmd.Parameters.AddWithValue("@id",  textBox_cardNumber.Text);
....

In this way you defer the job to recognize your data (the textbox text) as a string to the Framework code that knows how to correctly quote your value. Also you remove the possibilities of Sql Injection attacks

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
4
  "'" + textBox_cardNumber.Text + "'";

I hope I understood you!

Dominic B.
  • 1,897
  • 1
  • 16
  • 31
1

You can also try this, but this is not good practice, used always Parameter.

sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '" + textBox_cardNumber.Text +"'";
Amit
  • 15,217
  • 8
  • 46
  • 68
1

You can try this code:

SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '"
+  textBox_cardNumber.Text+"'";
0

Instead of string concatenation, you can should use parameterized sql instead. Because this kind of codes are open for SQL Injection attacks.

SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "SELECT DISTINCT transactionName FROM dbo.tbl
                      WHERE terminalId = @terminalID";

sqlcmd.Parameters.AddWithValue("@terminalID", textBox_cardNumber.Text);

A side note, take a look at SQL Injection Attacks by Example

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

You need to make use of prepared statements in which you use parameters.

Otherwise, you need to add quotes around your input string, but it will leave you open for SQL injection

nl-x
  • 11,762
  • 7
  • 33
  • 61