每个循环连续不会停止插入SQL Server

时间:2015-01-12 10:39:54

标签: c# sql-server

我有一个不会停止插入sql server的每个循环。

这是我的代码:

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(); 


            }
        }
    }
}

当我运行时,代码继续循环:

  

RunSecondSite();

它将继续插入,我不知道如何阻止它或在哪里放置正确的休息时间。

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

请告知。

2 个答案:

答案 0 :(得分:4)

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

从您的代码中,似乎“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();

答案 1 :(得分:1)

我认为你只需要替换

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

使用:

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

目前,您为每个列标题分别插入所有