C#插入到带有case语句的sql表中
我创建了一个InsertTable
方法到AigsAuthorityLayer
表,但有一些事件依赖于权限范围。如果scope is ==
系统,这将是等于1,当scope is ==
到共享组ID值是GroupId = aigsDB.GetDefGroup(Convert.ToString(context.Session["GroupID"])).Rows[0]["lSharingGid"].ToString();
如果是scope == to group
,这将是C#插入到带有case语句的sql表中
authority = aigsDB.GetDefGroupUser(Convert.ToString(context.Session["UserId"].ToString()));
对于editFlg,如果是等于一,它将返回true,如果没有,假
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;
}
}
我的问题是,我不知道我这样做是正确:(任何人都知道如果这个代码是否正确?谢谢
我没有看到为什么它在技术上可能无法正常工作,但您应该始终测试自己的代码。但是,可以进行一些改进。
首先,您应该使用参数化查询来防止SQL注入。其次,考虑c#使用语句来帮助处理完成时自动处理对象。例如:
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
语句,无论成功或错误SqlConnection
和SqlCommand
对象将被自动设置完成后,并释放所有资源。其次,通过使用SqlParameters,可以防止Sql注入。在你目前的方法中,有人可以输入(例如)“;”然后在其中一个值中输入“DELETE FROM”或“DROP TABLE”命令,以引发各种问题。
最后,如果你想捕捉一个错误,可以用try ... catch来包装上面的内容,并用/关于它做些事情。
希望有所帮助。
我建议你将参数行更新为'p.AddWithValue(“@ lGid”,GroupId)',这样它在读取时就不能与列名混淆。 –
垃圾,简单的错字。谢谢@ThorstenDittmar –
谢谢你们:)我现在会更新我的代码:)希望一切正常@JonBellamy – Lyn
为什么不使用[参数化查询](http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html)而不是字符串替换?顺便提一下,你的问题似乎有点不清楚。 –
@SonerGönül有一个重要的观点。你完全开放注入,并应改为参数化查询 –
我不知道该怎么做对不起@SonerGönül这只是第一次生病与C#工作。但是我的代码会工作吗? – Lyn