在C#中如何使用引号从文本框中获取值

Soh*_*ail 0 c# sql-server-2008

在我的程序中,我需要从数据库中获取价值,因此使用texbox以便客户端键入任何内容,我可以从数据库中搜索.

我的代码是

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

以上不是我的完整代码,但在我的代码中我使用的是textbox_cardNumber ...

我想用引号''

应该是这样的

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

所以我的问题是如何引用引号???

Ste*_*eve 6

使用像这样的参数化查询

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

sqlCmd.Parameters.AddWithValue("@id",  textBox_cardNumber.Text);
....
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以将作业延迟识别为将数据(文本框文本)识别为知道如何正确引用值的Framework代码的字符串.您还删除了Sql Injection攻击 的可能性