当我运行以下代码时,我收到一个错误:“必须声明标量变量”@objString“”。我可以不参数化动态SQL语句吗?有没有更好的写作方式?我有它工作,但它涉及动态插入名称和 userID 这显然是一个安全问题,因为该信息是从最终用户网页传入的。我想参数化这两个值以避免SQL注入问题。
private void setValue(Object obj, String name)
{
SqlConnection sqlConnection = SQLConnections.GetPortalConnection();
String sqlStatement = String.Empty;
string[] parameterNames;
string[] parameters;
switch (obj.GetType().ToString())
{
case "System.String":
string objString = obj.ToString();
sqlStatement = @"
declare @name nvarchar(" + name.Length + @");
declare @sql nvarchar(4000);
SET @name = '" + name + @"';
SET @sql = 'UPDATE [myoc4Data].[dbo].[users] SET ' + @name + ' = @objString WHERE [UserID] = @userID;'
exec sp_executesql @sql;";
string[] parameterNames = { "@objString", "@userID" };
string[] parameters = { objString, this.userID };
break;
default:
throw new Exception("Person.Portal.UserProfile.setValue: object type not found");
}
SQLConnections.ExecuteNonQuery(sqlStatement, parameterNames, parameters, sqlConnection);
sqlConnection.Close();
}
...
public static void ExecuteNonQuery(String sqlStatement, string[] parameterNames, object[] parameters, SqlConnection sqlConnection)
{
// Parameterized query
try
{
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand = new SqlCommand(sqlStatement, sqlConnection);
for (int x = 0; x < parameters.Length; x++)
{
switch (Type.GetTypeCode(parameters[x].GetType()))
{
case TypeCode.DateTime:
sqlCommand.Parameters.Add(parameterNames[x], SqlDbType.DateTime).Value = ((DateTime)parameters[x]).Year < 1753 ? DBNull.Value : parameters[x];
continue;
}
sqlCommand.Parameters.Add(new SqlParameter(parameterNames[x], parameters[x]));
}
sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new System.ArgumentException("Exception: Person: SQLConnections: Could not execute SQL statement: " + ex.Message);
}
}