猿问

C# 替换 foreach

我正在使用 Webservice GET 请求来获取有关客户的一些信息。我想为每个从请求返回的客户向数据库插入一条记录。


我现在有这个代码:


            var container = JsonConvert.DeserializeObject<MarkedCampaigns>(json);

            string insertDB = "";

            foreach (var item in container.items)

            {

                insertDB += "INSERT INTO TABLE (CampaignId,CookieId,Url) values(" + item.CampaignId + "," + item.VisitorExternalId + "," + item.Url + ");";

            }

            //EXECUTE STRING .

Container 是来自 Get 请求的响应。它包含一个 Item 属性,其中每个项目代表一个客户。


我的问题是,这是将记录插入到我的数据库的正确方法吗?或者有没有更简单的方法使用容器和一些我不熟悉的方法?


胡子哥哥
浏览 176回答 3
3回答

慕尼黑5688855

Sql 注入这个大问题的一部分,你正面临着一个决定。如果您要插入的元素很少,那么您可能可以使用@derpisher 的答案中所述的简单循环,但该答案需要为查询的每个元素调用数据库引擎,并且您需要自己定义所有参数。具有多个插入的单个命令文本更可取,因为您对数据库引擎进行了一次调用,并且在要插入许多记录的情况下,差异是显而易见的。但是,如果您想使用参数化查询,则最后一种方法很困难,因为您将需要为要插入的每个单个值提供一个参数。相反,我建议您尝试使用Dapper。使用这个简单的 ORM 库,你可以编写这个using(IDbConnection cnn = GetSqlConnection()){&nbsp; &nbsp; string cmdText = @"INSERT INTO TABLE (CampaignId,CookieId,Url)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;VALUES(@CampaignId, @VisitorExternalId, @Url)";&nbsp; &nbsp; cnn.Execute(cmdText, container.items);}这里的 GetSqlConnection 是一种返回已打开的连接实例的方法。cmdText 是要执行的命令,就好像您只有一个要插入的记录一样。诀窍是 Dapper 添加的 Execute 扩展命令,您可以在其中直接传递要插入的项目列表和命令文本。您只需要让参数名称与列表中的属性名称相匹配。

鸿蒙传说

我强烈建议使用准备好的语句。这将一方面消除每次解析查询的一些不必要的开销,另一方面它会迫使您使用参数化查询,这将防止类型转换问题——我认为这会发生在您的代码中,因为url大多数可能是某种字符类型,而您没有添加引号——以及 SQL 注入。string query = "INSERT INTO table(CampaignId, CookieId, Url) VALUES (@campaignid, @cookieid, @url)";using (SqlConnection c = new SqlConnection(connectstring)) {&nbsp; &nbsp; c.Open();&nbsp; &nbsp; SqlCommand cmd = new SqlCommand(query, c);&nbsp; &nbsp; cmd.Parameters.Add(new SqlParameter("@campaignid", SqlDbType.Int, 0)); //use appropriate type/size here&nbsp; &nbsp; cmd.Parameters.Add(new SqlParameter("@cookieid", SqlDbType.Int, 0)); //use appropriate type/size here&nbsp; &nbsp; cmd.Parameters.Add(new SqlParameter("@url", SqlDbType.NVarChar, 500)); //use appropriate type/size here&nbsp; &nbsp; cmd.Prepare();&nbsp; &nbsp; foreach (var item in container.items) {&nbsp; &nbsp; &nbsp; &nbsp; cmd.Parameters[0].value = item.CampaignId;&nbsp; &nbsp; &nbsp; &nbsp; cmd.Parameters[1].value = item.VisitorExternalId;&nbsp; &nbsp; &nbsp; &nbsp; cmd.Parameters[2].value = item.url;&nbsp; &nbsp; &nbsp; &nbsp; cmd.ExecuteNonQuery();&nbsp; &nbsp; }}

犯罪嫌疑人X

如果您只想对数据库进行一次调用以执行所有插入操作,那么一种选择是使用带有列表的存储过程:用于创建将存储我们的列表的类型的 sql:create type [dbo].CampaignList as table (CampaignId int,&nbsp; CookieId int, [Url] varchar(255))执行插入操作的存储过程create procedure [dbo].[spSaveCampaigns]&nbsp; &nbsp; @CampaignList CampaignList readonlyas&nbsp; &nbsp; insert into tblCampaigns (CampaignId, CookieId, [Url])&nbsp; &nbsp; select CampaignId, CookieId, [Url] from @CampaignList;调用它的 C#:public async Task InsertCampigns()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var campaigns = new List<Campaign> {new Campaign(1, 1, "bar"), new Campaign(2, 2, "foo") };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using (var sqlConnection = new SqlConnection(_connectionString))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using (var cmd = new SqlCommand("exec [dbo].[spSaveCampaigns] @CampaignList", sqlConnection))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await sqlConnection.OpenAsync().ConfigureAwait(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using (var table = new DataTable())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table.Columns.Add("CampaignId", typeof(int));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table.Columns.Add("CookieId", typeof(int));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table.Columns.Add("Url", typeof(string));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (var campaign in campaigns)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table.Rows.Add(campaign.CampaignId, campaign.CookieId, $"{campaign.Url}");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var parameters = new SqlParameter("@CampaignList", SqlDbType.Structured)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TypeName = "dbo.CampaignList",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Value = table&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cmd.Parameters.Add(parameters);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }您可以将创建数据表的代码从您的类型中提取到帮助程序中以使其更小。优点:参数化正确。我更喜欢调用存储过程而不是对数据库运行 sql(但您可能对此有不同的看法。)结果调用await InsertCampigns();广告系列 ID | CookieId | 网址1 | 1 | 酒吧2 | 2 | 富要在没有存储过程的情况下执行此操作,请参阅@Magnus 评论中的此链接https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters#passing-a-table-valued-parameter-to-a-parameterized-sql-statement
随时随地看视频慕课网APP
我要回答