【问题标题】:How to get last incremented id in SQL with single query如何使用单个查询在 SQL 中获取最后一个增量 id
【发布时间】: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/…
  • 你可能想看看@@identityscope_identity
  • @KarthikAMR 和 SqlChao - @@Identity 通常不是这些场景中的最佳选择。 read this.

标签: asp.net sql-server


【解决方案1】:

请注意,您的代码存在安全风险,因为它容易受到sql injection 攻击,正如Sean Lange 在 cmets 中正确写的那样。 此外,正如他所指出的,空接是一个问题。帮自己一个忙,永远不要使用空的 catch 块。

要获取当前会话中最后生成的标识值,您应该使用 Sql Server 的 SCOPE_IDENTITY() 函数。
请注意,如果您在表 SCOPE_IDENTITY() 上有一个而不是插入触发器,则 不会 为您提供正确的值。

您的代码应如下所示:

string insert = "insert into Articles values(@html, @text); select scope_identity()";

using (var con = new SqlConnection("<YOUR CONNECTION STRING HERE>"))
{
    using (var cmd = new SqlCommand(insert, con))
    {
        cmd.Parameters.Add("@html", SqlDbType.NVarChar).Value = html;
        cmd.Parameters.Add("@text", SqlDbType.NVarChar).Value = text;
        try
        {
            con.Open();
            var databaseId = cmd.ExecuteScalar();
            if (databaseId is int)
            {
                using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(string.Format(@"~\Articles\{0}.html", databaseId)), true))
                {
                    file.WriteLine(value.editor); // Write the file.
                }
                return msg;
            }
            else
            {
                return msg1;
            }
        }
        catch (Exception ex)
        {
            // Write to log, show an error message to the user                            
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多