使用参数化的 SqlCommand 会使我的程序免受 SQL 注入的影响吗? [英] Does using parameterized SqlCommand make my program immune to SQL injection?

查看:13
本文介绍了使用参数化的 SqlCommand 会使我的程序免受 SQL 注入的影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道SQL 注入相当危险.现在在我的 C# 代码中,我使用 编写参数化查询SqlCommand:

I'm aware that SQL injection is rather dangerous. Now in my C# code I compose parameterized queries with SqlCommand class:

SqlCommand command = ...;
command.CommandText = "SELECT * FROM Jobs WHERE JobId = @JobId;";
command.Parameters.Add("@JobId", SqlDbType.UniqueIdentifier ).Value = actualGuid;
command.ExecuteNonQuery();

这会自动使我的代码不受 SQL 注入的影响吗?我需要做一些额外的事情吗?

Will this automatically make my code immune to SQL injection? Do I have to do something extra?

推荐答案

我想说的是,对于参数化查询的特定示例,可能是规范的示例,是的,这就足够了.

I'd say for your particular, and probably canonical, example for parametrized queries, yes it is sufficient.

然而,人们有时会编写这样的代码

However, people sometimes write code like this

cmd.CommandText = string.Format("SELECT * FROM {0} WHERE col = @col;", tableName);
cmd.Parameters.Add("@col", ...);

因为根本无法将表名本身作为参数传递,并且有时存在这样做的愿望 - 是否被误导.然后似乎经常被忽视,tableName(除非可能只从一组不从任何输入派生的静态/常量值中读取)确实允许 SQL 注入.

because there is simply no way to pass the tablename itself as a parameter and the desire to do exists sometimes - misguided or not. It seems it is then often overlooked, that tableName (unless maybe only read from a set of static/constant values that do not derive from any input) indeed allows for SQL injection.

这篇关于使用参数化的 SqlCommand 会使我的程序免受 SQL 注入的影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆