C#用case语句插入sql表

时间:2014-03-07 11:58:03

标签: c# sql-server-2008

我正在InsertTable表创建一个AigsAuthorityLayer方法,但有一些事件取决于权限范围。如果scope is ==为系统,则等于1,当共享scope is ==时,组ID的值为GroupId = aigsDB.GetDefGroup(Convert.ToString(context.Session["GroupID"])).Rows[0]["lSharingGid"].ToString();,如果为scope == to group,则为< / p>

authority = aigsDB.GetDefGroupUser(Convert.ToString(context.Session["UserId"].ToString()));

对于editFlg,如果它等于1,它将返回true,如果不是,则返回false

CommonMethod.CheckLogin();
        string sqlWord = CommonDB.CreateSqlString("AigsAuthorityLayer", "*", "", "", "");
        context = HttpContext.Current;

        CommonDB comDB = new CommonDB(connection);     

        try

        {
            string sql = "INSERT INTO AigsAuthorityLayer (lGid, LayerNo, lAuthority, IEditFlg ) VALUES('{0}',{1}, {2},{3}')";
            sql = sql.Replace("{0}", GroupId);
            sql = sql.Replace("{1}", layerName.ToString());
            sql = sql.Replace("{2}", authority.ToString());
            sql = sql.Replace("{3}", editFlg.ToString());
            comDB.Open();
            comDB.AddNewRecord(sql);               

            {

            comDB.Close();
            comDB = null;
        }
            GroupId = "-1";
            authority = "-1";

            if (scope == "system")
            {
                return GroupId;
            }
            else if (scope == "sharing")
            {
                GroupId = aigsDB.GetDefGroup(Convert.ToString(context.Session["GroupID"])).Rows[0]["lSharingGid"].ToString();
            }
            else if (scope == "group")
            {
                authority = aigsDB.GetDefGroupUser(Convert.ToString(context.Session["UserId"].ToString()));
            }
            return true;
        }
           catch (Exception e)
         {
            throw logger.Error("InsertAigsAuthorityLayer", e);
         }
        finally
        {

            if (editFlg == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
            comDB.Close();
            comDB = null;
    }

}

我的问题是,我不知道我是否做对了:(任何人都知道这段代码是否正确?谢谢

1 个答案:

答案 0 :(得分:0)

我认为没有理由说它在技术上可能不起作用,但你应该总是测试自己的代码。但是,可以进行一些改进。

首先,您应该使用参数化查询来防止SQL注入。其次,考虑使用c#using语句来帮助处理完成后对象的自动处理。例如:

using(SqlConnection conn = new SqlConnection("<connection string here>")
{
    string cmdString = "INSERT INTO AigsAuthorityLayer (lGid, LayerNo, lAuthority, IEditFlg ) VALUES(@lGid, @layerNo, @lAuthority, @lEditFlag)";
    using(SqlCommand cmd = new SqlCommand(cmdString, conn)
    {

        cmd.CommandType = System.Data.CommandType.Text;

        SqlParameterCollection p = cmd.Parameters;

        // Build a parameter for each of @lGid, @layerNo, @lAuthority, @lEditFlag
        SqlParameter p1 = p.AddWithValue("@lGid", GroupId);
        p1.SqlDbType = System.Data.SqlDbType.Int; // Int assumed here

        // Repeat for other parameters
        ...

        // Run query as needed
        cmd.ExecuteNonQuery(); // Or appropriate method

    }
}

通过使用using语句,无论成功或错误如何,SqlConnectionSqlCommand对象将在完成并自动释放所有资源后自动处理。其次,通过使用SqlParameters,您可以防止Sql注入。在您当前的方法中,有人可以输入(例如)“;”然后在你的一个值中使用“DELETE FROM”或“DROP TABLE”命令来引发各种问题。

最后,如果您想捕获错误,可以将上面的内容包装在try ... catch中,并对其执行某些操作。

希望有所帮助。