【问题标题】:Inserting a List<> into SQL Server table将 List<> 插入 SQL Server 表
【发布时间】:2012-05-21 07:15:25
【问题描述】:

我有一个实体Report,我想将其值插入到数据库表中。必须插入Report 的以下属性:

reportID - int
RoleID - int
Created_BY = SYSTEM(default)
CURRENT_TIMESTAMP

现在问题出在第二个属性上。我有一份带有LIST&lt;ROLES&gt; 属性的报告。 ROLES 是一个定义明确的实体,它有一个ID 和一个NAME。我必须从这个列表中提取每个角色并将每个角色的 ID 插入到表中。

所以我的查询目前如下所示:

INSERT INTO REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED)
VALUES({0}, {1}, 'SYSTEM', CURRENT_TIMESTAMP)

我解析这些值的 C# 代码如下:

try
{
    StringBuilder _objSQL = new StringBuilder();
    _objSQL.AppendFormat(Queries.Report.ReportQueries.ADD_NEW_ROLES, report.ID, "report.MarjorieRoles.Add(MarjorieRole")); 
    _objDBWriteConnection.ExecuteQuery(_objSQL.ToString());
    _objDBWriteConnection.Commit();
    _IsRolesAdded = true;
}

所以请指导我如何从 C# 函数中添加角色

【问题讨论】:

  • 你考虑过 ORM 吗?使用 Linq to SQL 或实体框架,您可以在半小时内启动并运行它。还有 nHibernate。

标签: c# asp.net sql-server


【解决方案1】:

我假设您说的是 SQL(结构化查询语言),而您实际上是指 Microsoft SQL Server(实际的数据库产品) - 对吧?

您不能将整个列表作为一个整体插入 SQL Server - 您需要为每个条目插入一行。这意味着,您需要多次调用 INSERT 语句。

这样做:

// define the INSERT statement using **PARAMETERS**
string insertStmt = "INSERT INTO dbo.REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED) " + 
                    "VALUES(@ReportID, @RoleID, 'SYSTEM', CURRENT_TIMESTAMP)";

// set up connection and command objects in ADO.NET
using(SqlConnection conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn)
{
    // define parameters - ReportID is the same for each execution, so set value here
    cmd.Parameters.Add("@ReportID", SqlDbType.Int).Value = YourReportID;
    cmd.Parameters.Add("@RoleID", SqlDbType.Int);

    conn.Open();

    // iterate over all RoleID's and execute the INSERT statement for each of them
    foreach(int roleID in ListOfRoleIDs)
    {
      cmd.Parameters["@RoleID"].Value = roleID;
      cmd.ExecuteNonQuery();
    }

    conn.Close();
}      

【讨论】:

  • 是的,你是对的......它的 MS SQL Server 感谢您的帮助并在那里纠正我
  • 如何将列表作为 xml 传递?那会解决你的问题
  • @John:是的——你可以将它作为 XML 发送——但是你必须再次在 SQL Server 中“切碎”它,这也需要一些努力和代码......
  • 你可能会使用一个事务,所以如果出现问题它会回滚
【解决方案2】:

假设lstroles 是你的LIST&lt;ROLES&gt;

lstroles.ForEach(Role => 
   {            
       /* Your Insert Query like 
        INSERT INTO REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED)
        VALUES(REPORT_ID, Role.ID, {0}, {1}, 'SYSTEM', CURRENT_TIMESTAMP);

       Commit you query*\
   });

个人注意:提防 SQL 注入。

【讨论】:

  • 您应该将您的 SQL 语句连接在一起!这为 SQL 注入攻击打开了大门,而且从性能的角度来看也更慢(没有重用 SQL Server 执行计划!)
猜你喜欢
  • 2018-08-27
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 2021-02-19
相关资源
最近更新 更多