2011-03-14 22 views
1

在我的应用程序使用的String.format()对于这样的SQL的String.Format和SQL请求

Dim strSQL As String = "SELECT X FROM MY_TABLE WHERE Y <> {0} AND Z = '{1}'" 
    strSQL = String.Format(strSQL, otherObj.Y, myObj.Z) 

有一天,我做了使用SQL注入(带引号PARAMS一个全球性的“压力”测试,和这样的东西),并发现了很多错误...

什么是最好的方式在.NET中“打”它呢?是否有一个String.Format或其他常见的方式来正确(和安全地)在SQL查询中使用SQL参数。

你会推荐什么取代String.Format

回答

3

唯一完全安全的方式是不允许用户提供的数据到您的实际的SQL语句。相反,通过参数提供可变数据(例如您在格式字符串中使用的令牌)。

例如,

Using cmd As yourConnection.CreateCommand() 
    cmd.CommandText = "select x from my_table where y <> @y and z = @z" 

    cmd.Parameters.AddWithValue("@y", otherObj.Y) 
    cmd.Parameters.AddWithValue("@z", myObj.Z) 

    // etc. 
End Using 

(利用的AddWithValue假定这是一个SqlConnection,但代码不查找其他提供太大的不同,和概念是相同的)

8

改为使用参数化查询:防止SQL注入

Using conn as new SqlConnection(connString) 

    Dim command As new SqlCommand("select x from my_table " + & _ 
     "where y <> @param1 and z = @param2", conn); 

    command.Parameters.Add(new SqlParameter("@param1", otherObj.Y)); 
    command.Parameters.Add(new SqlParameter("@param2", myObj.Z)); 

    ' Execute the command and get results 

End Using 
+0

的OP的代码是VB.NET,但概念应该清楚。 – 2011-03-14 17:59:01