【发布时间】:2016-10-29 05:32:33
【问题描述】:
我正在从应用程序添加学生时进行验证。如果我运行以下查询
SELECT ID FROM Student WHERE Name =' " '+str+' " '
会产生如下错误:
列名“str”无效。
我的应用程序将生成 DBException。
我该如何解决这个问题?
编辑
String SName=txtBox1.Text;
String sql="select id from student where name = ' "+SName.Trim()+" ' ";
SqlConnection connection = null;
SqlDataReader reader = null;
try
{
connection = GetConnection();
SqlCommand command = new SqlCommand(sql, connection);
if (_sqltransection != null)
{
command.Transaction = _sqltransection;
}
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException ex)
{
throw new DBException(ex);
}
在哪里txtBox.Text=" '+str+' "
【问题讨论】:
-
您需要添加更多的单引号使其成为字符串,否则它将被解析为
SELECT ID FROM Student WHERE Name =divyesh -
加上你的代码看起来很容易被sql注入
-
什么是 divyesh?它是列名、变量/参数还是(失败的)字符串文字?
-
为什么需要双引号。您甚至可以在不嵌入双引号的情况下运行它。
-
在我的应用程序中,如果用户在文本框中输入类似“' +divyesh+'”的字符串,那么我该如何添加更多单引号?.
标签: c# sql asp.net sql-server-2008 ado.net