Table name and table field on SqlParameter C#?

提问者:

Hello.

I would like to know how to pass the table name and a table field name via SqlCommand on C#.

Tryied to do it the way it's done by setting the SqlCommand with the @ symbol but didn't work. Any ideas??

 

 

回答者:

I guess you are trying to execute a sql statement like

select @field from @table 

but that will not work. Sql can't have parameters on fieldnames or tablenames, just on values.

If my guess wasn't correct, please extens your question.

 

提问者:

Thanks... as I suposed :) already did a "trick" with a String Builder, but worries me the SQL Injection – 

 

回答者:

SqlCommand parameters can only be used to pass data. You cannot use them to modify the sql statement (such as adding additional fields to a select statement). If you need to modify the sql statement, I would suggest using a StringBuilder to create the tsql statement.

To elaborate further, .Net does not concatenate the sql before sending it to SqlServer (at least not in the straight-forward way you might expect). It actually calls a stored procedure and passes the arguments in separately. This allows Sql Server to cache the query plan and optimize the performance of you tsql.

If you were to write this SqlCommand...

var cmd = new SqlCommand("SELECT * FROM MyTable WHERE MyID = @MyID", conn); 
cmd
.Parameters.AddWithValue("@MyID", 1); 
cmd
.ExecuteNonQuery(); 
This is the tsql that is issued to Sql Server...

 

exec sp_executesql N'SELECT * FROM MyTable WHERE MyID = @MyID',N'@MyID int',@MyID=1

 

You can read more about sp_executesql on MSDN.

 

If you are worried about SQL injection, the SqlCommandBuilder class (and other DB specific versions of DbCommandBuilder) have a function called QuoteIdentifier that will escape your table name properly.

var builder = new SqlCommandBuilder(); 
string escTableName = builder.QuoteIdentifier(tableName); 

Now you can used the escaped value when building your statement and not have to worry about injection- but you should still be using parameters for any values.

 

本文来自:http://stackoverflow.com/questions/3128582/table-name-and-table-field-on-sqlparameter-c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值