以下函数获取参数并从sql server表返回第一个值。它的通用性非常易于使用,但它具有SQL注入的安全漏洞。任何人都可以帮助改变代码,使其成为参数或任何其他方式来保护SQL注入吗?
public static string getFieldValue(string tableName, string returnField, string whereCondition)
{
SqlConnection con = new SqlConnection(Utilities.ConnectionString());
SqlDataReader reader;
string returnValue;
try
{
string sql;
if (whereCondition != "")
sql = "SELECT " + returnField + " as ReturnField FROM " + tableName + " WHERE " + whereCondition;
else
sql = "SELECT " + returnField + " as ReturnField FROM " + tableName;
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
returnValue = reader["ReturnField"].ToString();
reader.Close();
return returnValue;
}
else
{
reader.Close();
return "";
}
}
catch (Exception err)
{
throw new ApplicationException(err.Message);
}
finally
{
con.Close();
con.Dispose();
}
}