【发布时间】:2016-04-04 13:39:54
【问题描述】:
我的要求我插入成功我想将最后一个增量 id 绑定到根文件夹文件名。id 在 SQL 中自动递增。我想在那个粗体部分的地方绑定最后一个递增的 id。
这是我的代码,请帮我解决这个问题:
string insert = "insert into Articles values('" + html+ "','" + text + "')";
try
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(@"~\Articles\**ID**.html"), true))
{
file.WriteLine(value.editor); // Write the file.
}
return msg;
}
else
{
return msg1;
}
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
【问题讨论】:
-
在您做任何其他事情之前,您需要阅读、理解和使用参数化查询。此代码易受 sql 注入攻击。您还应该阅读 C# 中的 USING 语句并将连接包装在其中。此外,你有一个空的捕获。这是非常糟糕的。如果出了什么问题,你甚至都不知道。我将这种反模式称为“try-squelch”。
-
想想如果
text变量包含这个值会发生什么:'); drop table articles;-- -
increment id是什么意思。如果您指的是进行插入的表中的ìdentity列,那么您可能希望将表Articles的 DDL 包含到您的问题中。不过,以下帖子可能对您的问题有帮助/相关:stackoverflow.com/questions/1920558/… -
你可能想看看
@@identity和scope_identity -
@KarthikAMR 和 SqlChao - @@Identity 通常不是这些场景中的最佳选择。 read this.
标签: asp.net sql-server