日期:2014-05-18  浏览次数:20385 次

帮忙看看这段代码有没有什么缺陷?
public static bool DelMessage(int UniqueID)
{
SqlConnection conn = DBAccess.conn;
string sqlcmd = "DELETE FROM Messages WHERE UniqueID='"+UniqueID+"'";
SqlCommand comm = new SqlCommand(sqlcmd, conn);
try
{
if(conn.State == ConnectionState.Closed) conn.Open();
int res = comm.ExecuteNonQuery();
if(1==res) return true;
else return false;
}
catch(Exception ex)
{
MailSender.SendException(ex);
return false;
}
finally
{
if(conn.State == ConnectionState.Open) conn.Close();
}
}
//像这样的代码是否有什么不足之处?

------解决方案--------------------
C# code

public static bool DelMessage(int uniqueID) //局部参数请小写
{
    bool flag = false;
    SqlConnection conn = DBAccess.conn;
    //用参数而不是拼接字符串
    string sqlcmd = "DELETE FROM Messages WHERE UniqueID = @UniqueID";
    SqlCommand comm = new SqlCommand(sqlcmd, conn);
    comm.Parameters.Add("@UniqueID", SqlDbType.VarChar).Value = uniqueID;
    try
    {
        if (conn.State == ConnectionState.Closed) 
            conn.Open();
        int res = comm.ExecuteNonQuery();
        if (1 == res) 
            flag = true;
    }
    catch (Exception ex)
    {
        MailSender.SendException(ex);
    }
    finally
    {
        if (conn.State == ConnectionState.Open) 
            conn.Close();
    }
    return flag;
}