Continuous For Each Loop 不会停止插入 SQL 服务器

Continuous For Each Loop Will not stop inserting into SQL Server

我有一个 for each 循环,它不会停止插入 sql 服务器。

这是我的代码:

using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using System.Data.SqlClient;
using System.Configuration;

namespace GooAnalyzer
{
    class Program
    {

        static void RunSecondSite()
        {
            var serviceAccountEmail = "543652534806-7lk19u13619g9pthghqger31sth9jpr4@developer.gserviceaccount.com";

            var certificate = new X509Certificate2(@"C:\Key\key.p12", "notasecret", X509KeyStorageFlags.Exportable);

            var credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics }
            }.FromCertificate(certificate));

            // Create the service.
            //Twistandtango
            var gas = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "GooAnalyzer",
            });

            var r = gas.Data.Ga.Get("ga:1860066", "2014-12-27", "2015-01-10", "ga:totalValue");

            //Specify some addition query parameters
            r.Dimensions = "ga:source,ga:medium,ga:campaign,ga:transactionId,ga:date";

            r.MaxResults = 100000000;

            //Execute and fetch the results of our query
            Google.Apis.Analytics.v3.Data.GaData d = r.Execute();

            foreach (var h in d.ColumnHeaders)
            {
                SqlConnection sqlCon = new SqlConnection("Data Source=UNDERGOD-PC\SQLEXPRESS;Initial Catalog=GooAnalyzer;Integrated Security=True");
                sqlCon.Open();
                foreach (var row in d.Rows)
                {

                    using (SqlCommand sqlCmd1 = new SqlCommand { CommandText = "INSERT INTO [GooData] ([Website], [gasource], [gamedium], [gacampaign], [gatransactionid], [gadate], [gatotalvalue], [Timeinserted]) VALUES (@Website, @gasource, @gamedium, @gacampaign, @gatransactionid, @gadate, @gatotalvalue, @Timeinserted)", Connection = sqlCon })
                    {
                        sqlCmd1.Parameters.AddWithValue("@Website", "4wheelparts.com");
                        sqlCmd1.Parameters.AddWithValue("@gasource", row[0]);
                        sqlCmd1.Parameters.AddWithValue("@gamedium", row[1]);
                        sqlCmd1.Parameters.AddWithValue("@gacampaign", row[2]);
                        sqlCmd1.Parameters.AddWithValue("@gatransactionid", row[3]);
                        sqlCmd1.Parameters.AddWithValue("@gadate", row[4]);
                        sqlCmd1.Parameters.AddWithValue("@gatotalvalue", row[5]);
                        sqlCmd1.Parameters.AddWithValue("@Timeinserted", DateTime.Now.ToString("MM-dd-yyyy"));
                        sqlCmd1.ExecuteNonQuery();

                    }

                }
                sqlCon.Close();
            }
        }



        static void Main(string[] args)
        {

            var serviceAccountEmail = "543652534806-7lk19u13619g9pthghqger31sth9jpr4@developer.gserviceaccount.com";

            var certificate = new X509Certificate2(@"C:\Key\key.p12", "notasecret", X509KeyStorageFlags.Exportable);

            var credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics }
            }.FromCertificate(certificate));

            // Create the service.
            //Twistandtango
            var gas = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "GooAnalyzer",
            });

            var r = gas.Data.Ga.Get("ga:1381000", "2014-12-27", "2015-01-10", "ga:totalValue");

            //Specify some addition query parameters
            r.Dimensions = "ga:source,ga:medium,ga:campaign,ga:transactionId,ga:date";

            r.MaxResults = 100000000;

            //Execute and fetch the results of our query
            Google.Apis.Analytics.v3.Data.GaData d = r.Execute();

            Console.WriteLine("Starting...");

            foreach (var h in d.ColumnHeaders)
            {
                SqlConnection sqlCon = new SqlConnection("Data Source=UNDERGOD-PC\SQLEXPRESS;Initial Catalog=GooAnalyzer;Integrated Security=True");
                sqlCon.Open();
                foreach (var row in d.Rows)
                {

                    using (SqlCommand sqlCmd1 = new SqlCommand { CommandText = "INSERT INTO [GooData] ([Website], [gasource], [gamedium], [gacampaign], [gatransactionid], [gadate], [gatotalvalue], [Timeinserted]) VALUES (@Website, @gasource, @gamedium, @gacampaign, @gatransactionid, @gadate, @gatotalvalue, @Timeinserted)", Connection = sqlCon })
                    {
                        sqlCmd1.Parameters.AddWithValue("@Website", "4wd.com");
                        sqlCmd1.Parameters.AddWithValue("@gasource", row[0]);
                        sqlCmd1.Parameters.AddWithValue("@gamedium", row[1]);
                        sqlCmd1.Parameters.AddWithValue("@gacampaign", row[2]);
                        sqlCmd1.Parameters.AddWithValue("@gatransactionid", row[3]);
                        sqlCmd1.Parameters.AddWithValue("@gadate", row[4]);
                        sqlCmd1.Parameters.AddWithValue("@gatotalvalue", row[5]);
                        sqlCmd1.Parameters.AddWithValue("@Timeinserted", DateTime.Now.ToString("MM-dd-yyyy"));
                        sqlCmd1.ExecuteNonQuery();

                    }

                }
                sqlCon.Close();
                RunSecondSite(); 


            }
        }
    }
}

当我 运行 this:

时代码继续循环

RunSecondSite();

它会继续插入,我不知道如何停止它或在哪里放置正确的中断。

我想稍后在控制台应用程序中调用此代码的更多方法,对每个循环也使用相同的方法。

请指教

我认为你只需要更换

foreach (var h in d.ColumnHeaders)
{
    SqlConnection sqlCon = ...
    sqlCon.Open();
    ... // snip
    sqlCon.Close();
}

与:

using(SqlConnection sqlCon = ...)
{
    sqlCon.Open();
    ... // snip
    sqlCon.Close();
}

目前您正在为每个 column-header.

单独且相同地插入所有行

您当前的逻辑是,每次迭代列 headers 时,您都将每一行添加到数据库中,从而导致插入相同的行。

从您的代码来看,"h" 似乎从未被使用过..

只需删除:

foreach (var h in d.ColumnHeaders)
{
...
}

成为:

SqlConnection sqlCon = new SqlConnection("Data Source=UNDERGOD-PC\SQLEXPRESS;Initial Catalog=GooAnalyzer;Integrated Security=True");
sqlCon.Open();

foreach (var row in d.Rows)
{
    using (SqlCommand sqlCmd1 = new SqlCommand { CommandText = "INSERT INTO [GooData] ([Website], [gasource], [gamedium], [gacampaign], [gatransactionid], [gadate], [gatotalvalue], [Timeinserted]) VALUES (@Website, @gasource, @gamedium, @gacampaign, @gatransactionid, @gadate, @gatotalvalue, @Timeinserted)", Connection = sqlCon })
    {
         sqlCmd1.Parameters.AddWithValue("@Website", "4wheelparts.com");
         sqlCmd1.Parameters.AddWithValue("@gasource", row[0]);
         sqlCmd1.Parameters.AddWithValue("@gamedium", row[1]);
         sqlCmd1.Parameters.AddWithValue("@gacampaign", row[2]);
         sqlCmd1.Parameters.AddWithValue("@gatransactionid", row[3]);
         sqlCmd1.Parameters.AddWithValue("@gadate", row[4]);
         sqlCmd1.Parameters.AddWithValue("@gatotalvalue", row[5]);
         sqlCmd1.Parameters.AddWithValue("@Timeinserted", DateTime.Now.ToString("MM-dd-yyyy"));
         sqlCmd1.ExecuteNonQuery();
     }
}
sqlCon.Close();