简体   繁体   English

尝试使用ASP.NET和C#将csv和xls文件导入SQL数据库

[英]Trying to import csv and xls files to an SQL database using ASP.NET and C#

I am a student and quite new to programming, and I was given a task to do using ASP.NET and C#, without being taught either. 我是一名学生,对编程还很陌生,因此我被赋予了使用ASP.NET和C#的任务,而没有一个人受教。 The plan is to learn to teach ourselves. 该计划是学会自学。

The task I am stuck on is making a website import from a CSV or XLS file to a SQL database of last year's room bookings around the campus. 我的任务是将网站从CSV或XLS文件导入到校园周围去年的客房预订的SQL数据库中。

While I have learned a few things by following tutorials, I am stuck on finding a way to program c# to "read" a csv file (with the delimiter used to separate entries being the comma ",") and an xls file into a table using Microsoft's SQL database. 通过以下教程我学到了一些东西,但是我仍然想找到一种方法来编程c#以“读取”一个csv文件(分隔符用于将条目分隔为逗号“,”)和一个xls文件到表中使用Microsoft的SQL数据库。

So, what I did is, after having downloaded Visual Studio, and getting started with asp.net's webforms, I started by creating a button on the .aspx form to trigger the import upon being clicked: 因此,我所做的是,下载了Visual Studio,并开始使用asp.net的Web窗体后,我首先在.aspx窗体上创建一个按钮以在单击时触发导入:

 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Import_button_Click"/>

I would name my function "Import_Button_Click" 我将函数命名为“ Import_Button_Click”

Here, I found at a tutorial a .dll library called Filehelpers. 在这里,我在教程中找到了一个名为Filehelpers的.dll库。 I it looked promising, so I gave it a try. 我看起来很有前途,所以我尝试了一下。 I added a reference of it at Visual Studio and also added "using Filehelpers;" 我在Visual Studio中添加了对它的引用,还添加了“使用Filehelpers”; at the beginning of the C# form. 在C#表单的开头。

Here is a link: http://filehelpers.sourceforge.net/ 这是一个链接: http : //filehelpers.sourceforge.net/

So, I use: 因此,我使用:

FileHelperEngine engine = new FileHelperEngine(typeof(CSVfile));

and

 CSVfile[] result = engine.ReadFile("C:\\CSVDATA\\previousyear.csv") as CSVfile[];

to make it read the CSV file. 使其读取CSV文件。 Meanwhile, I create a class to store every entry of the CSV file as a variable: 同时,我创建了一个类来存储CSV文件的每个条目作为变量:

 [DelimitedRecord(",")]
    public class CSVfile  //CSVfile class being defined
    {
        public int Request_ID;
        public int Priority;
        public int Module_ID;
        public string Day;
        public string Start_Time;
        public int Length;
        public string Park;
        public int Students;
        public string Room_Code;
        public string Status;
        public int Semester_ID;
        public int Linked_Request;
      public int Week_1;
        public int Week_2;
        public int Week_3;
        public int Week_4;
        public int Week_5;
        public int Week_6;
        public int Week_7;
        public int Week_8;
        public int Week_9;
        public int Week_10;
        public int Week_11;
        public int Week_12;
        public int Week_13;
        public int Week_14;
        public int Week_15;

} }

and after that, right below where it reads previousyear.csv, I do the loop that will take every entry and put it at the correct variables: 然后,在读取前一year.csv的位置下面,我执行将获取每个条目并将其放入正确变量的循环:

 DataTable table = new DataTable();
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
       table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(string));
        table.Columns.Add(" ", typeof(string));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(string));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(string));
        table.Columns.Add(" ", typeof(string));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int)); 
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));
        table.Columns.Add(" ", typeof(int));

foreach (CSVfile row in result) { Console.WriteLine(row.Request_ID + " " + row.Priority); foreach(结果中的CSVfile行){Console.WriteLine(row.Request_ID +“” + row.Priority);

            table.Rows.Add(row.Request_ID, row.Priority);

        }

but the thing is, I can't make it output the results anywhere, not even using a gridview 但问题是,我什至无法使用gridview使其在任何地方输出结果

Also, it turns that it's quite troublesome to run it on other computers with the added library. 而且,事实证明,在具有添加的库的其他计算机上运行它非常麻烦。

Today, a teammate of mine gave me the SQL code that I should use to put my variables to the database, which is this: 今天,我的一个队友给了我我应该用来将变量放入数据库的SQL代码,它是:

public string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["team03ConnectionString"].ConnectionString;
        //the "ConnStringName" is the name of your Connection String that was set up from the Web.Config


    }

    protected void BookRoom_Click(object sender, EventArgs e)
    {


        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(GetConnectionString());
        // string sql = "INSERT INTO tests (column6,Column2,Column3,Column4,Column5) VALUES (@Val1,@Val2,@Val3,@Val4,@Val5)";
        // string sql = "Insert INTO Requests (Priority, Module_ID, Day,Start_Time, Length, Park, Students, Room_Code, Status, Semester_ID, Week_1,Week_2,Week_3,Week_4,Week_5,Week_6,Week_7,Week_8,Week_9,Week_10,Week_11,Week_12,Week_13,Week_14,Week_15) VALUES (@Priority, @Module_ID, @Day,@Start_Time, @Length, @Park, @Students, @Room_Code, @Status, @Semester_ID, @Week_1, @Week_2, @Week_3, @Week_4, @Week_5, @Week_6, @Week_7, @Week_8, @Week_9, @Week_10, @Week_11, @Week_12, @Week_13, @Week_14, @Week_15)";
        string sql = "Insert INTO Requests (Priority, Module_ID, Day,Start_Time, Length, Park, Students, Room_Code, Status,Room_Allocated, Semester_ID, Week_1,Week_2,Week_3,Week_4,Week_5,Week_6,Week_7,Week_8,Week_9,Week_10,Week_11,Week_12,Week_13,Week_14,Week_15) OUTPUT INSERTED.Request_ID VALUES (@Priority, @Module_ID, @Day,@Start_Time, @Length, @Park, @Students, @Room_Code, @Status,@Room_Allocated, @Semester_ID, @Week_1, @Week_2, @Week_3, @Week_4, @Week_5, @Week_6, @Week_7, @Week_8, @Week_9, @Week_10, @Week_11, @Week_12, @Week_13, @Week_14, @Week_15)";

        try
        {


            conn.Open();
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@Priority", "0");
            cmd.Parameters.AddWithValue("@Module_ID", moduleSelect.Text);
            cmd.Parameters.AddWithValue("@Day", Day.Text);
            cmd.Parameters.AddWithValue("@Start_Time", StartTime.Text);
            cmd.Parameters.AddWithValue("@Length", "1");
            cmd.Parameters.AddWithValue("@Park", Request.QueryString["Pk"].ToString());
            cmd.Parameters.AddWithValue("@Students", NumOfStudents.Text);
            cmd.Parameters.AddWithValue("@Room_Code", roomChosen.Text);
            cmd.Parameters.AddWithValue("@Status", "Pending");
            cmd.Parameters.AddWithValue("@Room_Allocated", roomChosen.Text);
            cmd.Parameters.AddWithValue("@Semester_ID", "7");
            cmd.Parameters.AddWithValue("@Week_1", weeknumber1.Text);
            cmd.Parameters.AddWithValue("@Week_2", weeknumber2.Text);
            cmd.Parameters.AddWithValue("@Week_3", weeknumber3.Text);
            cmd.Parameters.AddWithValue("@Week_4", weeknumber4.Text);
            cmd.Parameters.AddWithValue("@Week_5", weeknumber5.Text);
            cmd.Parameters.AddWithValue("@Week_6", weeknumber6.Text);
            cmd.Parameters.AddWithValue("@Week_7", weeknumber7.Text);
            cmd.Parameters.AddWithValue("@Week_8", weeknumber8.Text);
            cmd.Parameters.AddWithValue("@Week_9", weeknumber9.Text);
            cmd.Parameters.AddWithValue("@Week_10", weeknumber10.Text);
            cmd.Parameters.AddWithValue("@Week_11", weeknumber11.Text);
            cmd.Parameters.AddWithValue("@Week_12", weeknumber12.Text);
            cmd.Parameters.AddWithValue("@Week_13", weeknumber13.Text);
            cmd.Parameters.AddWithValue("@Week_14", weeknumber14.Text);
            cmd.Parameters.AddWithValue("@Week_15", weeknumber15.Text);
            //cmd.CommandType = System.Data.CommandType.Text;
            //Int32 newId = (Int32)cmd.ExecuteScalar();
            cmd.ExecuteNonQuery();


        } //End of try

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }

        catch (FormatException ee)
        {

            System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
        }

        catch (System.Exception eeee)
        {
            System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");

        }

        finally
        {
            conn.Close();
        }
    }//End of insertInfor()

}

and he told me that I had until Sunday to figure out the rest. 他告诉我,直到星期天我才能弄清其余的一切。

So having said all these, I am not looking for someone to do my coursework, but rather advice from experienced people here, because asp.net seems so confusing. 综上所述,我并不是要找人来做我的课程,而是要从这里的有经验的人那里获得建议,因为asp.net似乎很令人困惑。 Is there a way to do this without using external libraries? 有没有一种方法可以不使用外部库? Can I make gridview show the table from the database? 我可以使gridview显示数据库中的表吗? What would be the best approach? 最好的方法是什么?

Thanks a lot! 非常感谢!

UPDATE: 更新:

@Tim @蒂姆

Thanks again for all the help! 再次感谢您提供的所有帮助!

This is what I have at the moment: 这是我目前所拥有的:

        using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.OleDb;
    using FileHelpers;


namespace ImportPage
{

    public class CSVFile
    {

        public int Request_ID { get; set; }
        public int Priority { get; set; }
        //...

    }




    public class CSV
    {
        public string GetConnectionString()
        { return System.Configuration.ConfigurationManager.ConnectionStrings["team03ConnectionString"].ConnectionString; }


        protected void button1_Click(object sender, EventArgs e)
        {

            List<CSVFile> entries = new List<CSVFile>();

            using (TextFieldParser parser = new TextFieldParser(@"C:\CSVDATA\PreviousYear.csv"))
            {

                parser.TextFieldType = FieldType.Delimited;
                parser.Delimiters = new string[] { "," };
                string[] fields;

                while (!parser.EndOfData)
                {
                    fields = parser.ReadFields();
                    entries.Add(new CSVFile()
                    {
                        Request_ID = Convert.ToInt32(fields[0]),
                        Priority = Convert.ToInt32(fields[1]),

                        //...

                    });
                }

            }


        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(GetConnectionString());

        string sql = "Insert INTO Requests (Priority) OUTPUT INSERTED.Request_ID VALUES (@Priority)";

        try
        {


            conn.Open();
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@Priority", "0");


            cmd.ExecuteNonQuery();


        } //End of try

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }

        catch (FormatException ee)
        {

            System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
        }

        catch (System.Exception eeee)
        {
            System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");

        }

        finally
        {
            conn.Close();
        }


}


        }
}

I am attempting to make it work for a CSV file with only 2 entries for starters: Request ID and Priority, to make something simple and build upon it. 我正在尝试使其仅对初学者有2个条目的CSV文件起作用:“请求ID”和“优先级”,以使其变得简单并在此基础上进行构建。

To make things short, I am confused on how to put my code, your code and my teammates code to make something working (as I dont understand everything in the code) 简而言之,我对如何放置我的代码,您的代码和我的队友代码感到困惑,因为某些代码无法正常工作(因为我不了解代码中的所有内容)

UPDATE 2: 更新2:

Here is my .aspx code, nothing special, just 1 button , 1 gridview 这是我的.aspx代码,没什么特别的,只有1个按钮,1个gridview

<!DOCTYPE html>
<script runat="server">

    Protected Sub Import_button_Click(sender As Object, e As EventArgs)

    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs)

    End Sub
</script>
<html lang="en">

  <head>
    <meta charset="utf-8">

    <title>Timetabling Support Website</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Loading Bootstrap -->
    <link href="css/bootstrap.css" rel="stylesheet">

    <!-- Loading Flat UI -->
    <link href="css/flat-ui.css" rel="stylesheet">

     <!-- Loading Unsemantic -->
    <link href="css/unsemantic-grid-responsive.css" rel="stylesheet"> 

    <!-- Loading Personalized Style -->
    <link href="css/style.css" rel="stylesheet"> 
    <link rel="shortcut icon" href="images/favicon.ico">  


    <!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. -->
    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
    <![endif]-->
  </head>

  <body>
      <form id="form1" runat="server">
    <div class="grid-container">

      <div class="header grid-100">
        <div class="banner grid-70">
          <img src="images/banner3.png" id="banner" alt="Loughborough Uni Logo" />
        </div>
        <div class="logout grid-30">
          <p id="logout"> Welcome, Computer Science Timetabler. | <a href="index.html">Logout</a></p>
        </div>
      </div>


      <div class="navbar navbar-inverse">
          <div class="navbar-inner">
            <ul class="nav">
              <li>
                <a href="home.html">
                  Home
                </a>
              </li>
              <li>
                <a href="#">
                  Requests
                </a>
                <ul>
                  <li>
                    <a href="request_new.html">New Request</a>
                  </li>
                  <li>
                    <a href="request_import.html">Import Requests</a>
                  </li>
                  <li>
                    <a href="request_current.html">Current Requests</a>
                  </li>
                  <li>
                    <a href="request_adhoc.html">Ad-Hoc Request</a>
                  </li>
                </ul> <!-- /Sub menu -->
              </li>
              <li>
                <a href="room_availability.html">
                  Room Availability
                </a>
              </li>
              <li>
                <a href="#">
                  History
                </a>
                <ul>
                  <li>
                    <a href="#">Semester 1</a>
                    <ul>
                      <li>
                        <a href="history_s1priority.html">Priority Round</a>
                      </li>
                      <li>
                        <a href="history_s1round1.html">Round 1</a>
                      </li>
                      <li>
                        <a href="history_current.html">Round 2</a>
                      </li>
                      <li>
                        <a href="history.html">Final Allocations</a>
                      </li>
                    </ul> <!-- /Sub menu -->
                  </li>
                  <li>
                    <a href="#">Semester 2</a>
                    <ul>
                      <li>
                        <a href="history.html">Priority Round</a>
                      </li>
                      <li>
                        <a href="history.html">Round 1</a>
                      </li>
                      <li>
                        <a href="history.html">Round 2</a>
                      </li>
                      <li>
                        <a href="history.html">Final Allocations</a>
                      </li>
                    </ul> <!-- /Sub menu -->
                  </li>
                </ul> <!-- /Sub menu -->
              </li>
              <li>
                <a href="#">
                  Maintenance
                </a>
                <ul>
                  <li>
                    <a href="module_add.html">Add Module</a>
                  </li>
                  <li>
                    <a href="module_edit.html">Edit Module</a>
                  </li>
                </ul> <!-- /Sub menu -->
              </li>
              <li>
                <a href="help.html">
                  Help
                </a>
              </li>
            </ul>
          </div><!--/.nav-collapse -->
      </div>

      <div class="content center">
          <h1>Import Request
          </h1>
         <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Import_button_Click"/>
          <asp:GridView ID="GridView1" runat="server">


          </asp:GridView>

           </div>

         <div class="grid-100 footer">
        <p>Copyright © 2013 Team 3 Timetabling Support Website</p> 
      </div>

    </div> <!-- /container -->


      <asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
    <!-- Load JS here for greater good =============================-->
    <script src="js/jquery-1.8.2.min.js"></script>
    <script src="js/jquery-ui-1.10.0.custom.min.js"></script>
    <script src="js/jquery.dropkick-1.0.0.js"></script>
    <script src="js/custom_checkbox_and_radio.js"></script>
    <script src="js/custom_radio.js"></script>
    <script src="js/jquery.tagsinput.js"></script>
    <script src="js/bootstrap-tooltip.js"></script>
    <script src="js/jquery.placeholder.js"></script>
    <script src="http://vjs.zencdn.net/c/video.js"></script>
    <script src="js/application.js"></script>
    <!--[if lt IE 8]>
      <script src="js/icon-font-ie7.js"></script>
      <script src="js/icon-font-ie7-24.js"></script>
    <![endif]-->
      </form>
  </body>
</html>

It appears to have lots of problems with this part of the code: 这部分代码似乎有很多问题:

 string sql = "Insert INTO Requests (Priority); 
                   OUTPUT INSERTED.Request_ID 
                   VALUES (@Priority)";

Update 3: 更新3:

Ok, fixed that piece of code. 好的,修复了这段代码。 Just had to put it all at the same row. 只需将所有内容放在同一行。 Now there is only 1 error when I try to build the app: 现在,当我尝试构建应用程序时只有1个错误:

Error 3 The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?) 错误3找不到类型或名称空间名称'SqlCommand'(您是否缺少using指令或程序集引用?)

So, SqlCommand is not recognized. 因此,无法识别SqlCommand。 Do I need to add a reference or something for it to be recognized? 我需要添加参考或其他东西才能被识别吗? The same goes for SqlConnection SqlConnection也是如此

Update 4 更新4

This is the code I am using now, as I make it work in Visual Studio 这是我现在使用的代码,因为我可以在Visual Studio中使用它

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.VisualBasic.FileIO;
using System.Data.SqlClient;

namespace ImportPage
{

    public class CSVFile
    {

        public int Request_ID { get; set; }
        public int Priority { get; set; }
        public int Module_ID { get; set; }
        //...

    }




    public class CSV
    {
        public string GetConnectionString()
        { return System.Configuration.ConfigurationManager.ConnectionStrings["team03ConnectionString"].ConnectionString; }


        protected void button1_Click(object sender, EventArgs e)
        {

            List<CSVFile> entries = new List<CSVFile>();

            using (TextFieldParser parser = new TextFieldParser(@"PreviousYear.csv"))
            {

                parser.TextFieldType = FieldType.Delimited;
                parser.Delimiters = new string[] { "," };
                string[] fields;

                while (!parser.EndOfData)
                {
                    fields = parser.ReadFields();
                    entries.Add(new CSVFile()
                    {
                        Request_ID = Convert.ToInt32(fields[0]),
                        Priority = Convert.ToInt32(fields[1]),
                        Module_ID = Convert.ToInt32(fields[2])
                        //...

                    });
                }

            }


        using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{


    string sql = "Insert INTO Requests (Priority, Module_ID) OUTPUT INSERTED.Request_ID VALUES (@Priority, @Module_ID)";

    try
    {

        conn.Open();

        foreach (CSVFile entry in entries)
        {

            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {

                cmd.Parameters.AddWithValue("@Priority", entry.Priority);
                cmd.Parameters.AddWithValue("@Module_ID", entry.Module_ID);

                // ...
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
        throw new Exception(msg);
    }
    catch (FormatException ee)
    {
        System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
    }
    catch (System.Exception eeee)
    {
        System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");

    }
}


}










}


        }

There is a little known but surprising useful file parser in the .NET framework - Microsoft.VisualBasic.FileIO.TextFieldParser (despite it's name, it can be used in C#). .NET框架中有一个鲜为人知但令人惊讶的有用的文件解析器-Microsoft.VisualBasic.FileIO.TextFieldParser (尽管它的名称是,可以在C#中使用)。 To give an abbreviated example of its use, I would do the following. 为了给出其用法的简短示例,我将执行以下操作。

First, I'd implement automatic properties in your CSVFile class, rather than public fields: 首先,我将在您的CSVFile类中实现自动属性,而不是在公共字段中实现:

public class CSVFile
{

    public int Request_ID { get; set; }
    public int Priority { get; set; }
    public int Module_ID { get; set; }
    public string Day { get; set; }
    public string Start_Time { get; set; }
    // and so on
}

Next, I would build a List<T> (generic list) of CSVFile instances, populating each instance with the data from the CSV file (using TextFieldParser ). 接下来,我将构建一个CSVFile实例的List<T> (通用列表), CSVFile使用CSV文件中的数据(使用TextFieldParser )填充每个实例。 You'll need to add a reference to Microsoft.VisualBasic.FileIO and the using directive. 您需要添加对Microsoft.VisualBasic.FileIOusing指令的引用。

using Microsoft.VisualBasic.FileIO;

List<CSVFile> entries = new List<CSVFile>();

using (TextFieldParser parser = new TextFieldParser(@"C:\CSVDATA\PreviousYear.csv"))
{

    parser.TextFieldType = FieldType.Delimited;
    parser.Delimiters = new string[]{','};
    string[] fields;

    while (!parser.EndOfData)
    {
        fields = parser.ReadFields();
        entries.Add(new CSVFile() { Request_ID = Convert.ToInt32(fields[0]), 
                                    Priority = Convert.ToInt32(fields[1]),
                                    Module_ID = Convert.ToInt32(fields[2]),
                                    Day = fields[3],
                                    Start_Time = fiedls[4],
                                    // and the rest of the properties, casting as needed
                                   };
    }
}

The end result of the above code snippet will be a List<T> of CSVFile s. 上面代码片段的最终结果将是CSVFileList<T> With the automatic properties, you can initialize the instance when you create it and add it to the list entries . 使用自动属性,您可以在创建实例时对其进行初始化,并将其添加到列表entries

You can then bind the list to a GridView like this: 然后,您可以像这样将列表绑定到GridView

GridView1.DataSource = entries;
GridView1.DataBind();

It's not clear from your question whether you're updating the table with all the entries or just selected ones. 从您的问题尚不清楚,您是要使用所有条目还是仅选择条目来更新表。 Let's assume (for purposes of this example) that it's all of them. 让我们假设(出于本示例的目的)所有这些都是。 Your teammate has given you what you need - put it inside a loop and you can enter all the data from the CSV file into the SQL database, like this: 您的队友已经满足了您的需求-将其放入循环中,您可以将CSV文件中的所有数据输入到SQL数据库中,如下所示:

// It's considered best practice to use a `using` block with `SqlConnection`
// (among other objects). The `using` block ensures the connection is properly
// disposed of once execution leaves the block.
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{

    // I'm breaking into individual lines here simply 
    // so it's easier to read on SO
    string sql = "Insert INTO Requests (Priority, Module_ID, Day, 
                                        Start_Time, Length, Park, 
                                        Students, Room_Code, Status,
                                        Room_Allocated, Semester_ID,
                                        Week_1, Week_2, Week_3, Week_4,
                                        Week_5, Week_6, Week_7, Week_8,
                                        Week_9, Week_10, Week_11, Week_12,
                                        Week_13, Week_14, Week_15) 
                   OUTPUT INSERTED.Request_ID 
                   VALUES (@Priority, @Module_ID, @Day, @Start_Time, 
                           @Length, @Park, @Students, @Room_Code,
                           @Status, @Room_Allocated, @Semester_ID, 
                           @Week_1, @Week_2, @Week_3, @Week_4, @Week_5, 
                           @Week_6, @Week_7, @Week_8, @Week_9, @Week_10, 
                           @Week_11, @Week_12, @Week_13, @Week_14, @Week_15)";

    try
    {

        conn.Open();

        foreach (CSVFile entry in entries)
        {

            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {

                cmd.Parameters.AddWithValue("@Priority", entry.Priority);
                cmd.Parameters.AddWithValue("@Module_ID", entry.Module_ID);
                cmd.Parameters.AddWithValue("@Day", entry.Day);
                cmd.Parameters.AddWithValue("@Start_Time", entry.Start_Time);
                // And so on

                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
        throw new Exception(msg);
    }
    catch (FormatException ee)
    {
        System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
    }
    catch (System.Exception eeee)
    {
        System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");

    }
} // Since we're in a `using` block, there is no need for the `finally` block 
  // close the connection.

By the way, kudos to your teammate for showing you paramaterized SQL queries - these are very important to defend against SQL Injection Attacks. 顺便说一句,向您的队友致以诚挚的敬意,向您展示了参数化的SQL查询-这些对于防御SQL注入攻击非常重要。

Hopefully this will help you. 希望这会对您有所帮助。

You need to create a table with the same fields from your csv file for example your csv file have id,FirstName,LastName,BirthDate 您需要使用csv文件中的相同字段创建一个表,例如您的csv文件具有id,FirstName,LastName,BirthDate

The location of the file is C:\\csvtest.txt 该文件的位置是C:\\ csvtest.txt

1,James,Smith,19750101 1,詹姆斯·史密斯,19750101

2,Meggie,Smith,19790122 2,Meggie,Smith,19790122

3,Robert,Smith,20071101 3,罗伯特·史密斯,20071101

4,Alex,Smith,20040202 4,亚历克斯·史密斯20040202

CREATE TABLE tablename
(ID INT,
FirstName VARCHAR(40),
LastName VARCHAR(40),
BirthDate SMALLDATETIME)
GO

After Creation of the table you can insert the csv data in this table by following command. 创建表后,可以通过以下命令在该表中插入csv数据。 You need to pass the your csv file location. 您需要传递您的csv文件位置。

BULK
INSERT tablename
FROM 'c:\csvtest.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM