我试图使用文本框作为gridview的过滤器,最后编写了这段代码:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
SqlDataSource1.ConnectionString = "connection string goes here"
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE WHERE area LIKE '" + TextBox1.Text + "%'"
'GridView1.DataSource = SqlDataSource1.SelectCommand
SqlDataSource1.DataBind()
GridView1.DataBind()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
有效。但是我觉得它太简单和不安全了。你能否告诉我应该如何以更“专业”(真实)的方式来做?
答案 0 :(得分:1)
内联SQL不安全,您很容易受到SQL注入攻击,因为可以在该文本框中键入对数据库极其有害的内容,并且不会检查该值。
阅读Understanding SQL Injection and Creating SQL Injection Proof ASP.NET Applications
在SQL Server中使用参数化SQL或存储过程。
答案 1 :(得分:1)
要使用参数化的sql语句,请添加一个带有sql数据类型和默认值的select参数。
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
SqlDataSource1.ConnectionString = "connection string goes here"
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE WHERE area LIKE @area"
'GridView1.DataSource = SqlDataSource1.SelectCommand
SqlDataSource1.SelectParameters.Add(New Parameter("area", DbType.String,TextBox1.Text))
SqlDataSource1.DataBind()
GridView1.DataBind()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub