使用FileUpload从.CSV导入数据到SQL?

时间:2012-05-02 15:31:17

标签: c# asp.net sql

我有一个包含评论的.CSV文件,我将以编程方式将内容从FileUpload控件传输到SQL数据库。我遇到的问题是我的控件正在运行,但我没有看到我的数据库中填充了任何数据。这是我的代码:

标记

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Button ID="Button1" runat="server"onclick="Button1_Click"                                                               Text="Button" />
<asp:Label ID="Label1" runat="server"></asp:Label>



Code Behind

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {

            string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);

            if (fileExt == ".csv")
            {
                OleDbConnection oconn = new     OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + FileUpload1 + ";     Extended Properties=Excel 8.0");

                try
                {
                    OleDbCommand ocmd = new OleDbCommand("SELECT * FROM [AudioPR$]",     oconn);
                    oconn.Open();

                    OleDbDataReader odr = ocmd.ExecuteReader();
                    string Device = "";
                    string Source = "";
                    string Reviewer = "";
                    string Datetime = "";
                    string Links = "";
                    string Content = "";
                    string Subject = "";

                    while (odr.Read())
                    {

                        Device = valid(odr, 0);
                        Source = valid(odr, 1);
                        Reviewer = valid(odr, 2);
                        Datetime = valid(odr, 3);
                        Links = valid(odr, 4);
                        Content = valid(odr, 5);
                        Subject = valid(odr, 6);

                        InsertDataIntoSql(Device, Source, Reviewer, Datetime, Links,     Content, Subject);

                    }

                    oconn.Close();

                 }

                 catch (Exception ee)
                {
                    Label1.Text = ee.Message;
                    Label1.ForeColor = System.Drawing.Color.Red;
                }
                finally
                {
                    Label1.Text = "Data Inserted Successfully";
                    Label1.ForeColor = System.Drawing.Color.Green;

                }

            }

            else
            {
                Label1.Text = "Only .csv files allowed!";

            }

        }

         else
            {

            Label1.Text = "You have not specified a file!";

            }

       }



    protected string valid(OleDbDataReader myreader, int stval)

    {
        object val = myreader[stval];
        if (val != DBNull.Value)
        {

            return val.ToString();
        }
        else
        {
            return Convert.ToString(0);
        }


    }

    public void InsertDataIntoSql(string Device, string Source, string Reviewer, string     Datetime, string Links, string Content, string Subject)

    {
        SqlConnection conn = new SqlConnection("Data Source=CI0000000879107\\BENSON;    Initial Catalog=PRClips Mail;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "INSERT INTO AudioPR(Device, Source, Reviewer, Datetime,     Links, Content, Subject) VALUES(@Device, @Source, @Reviewer, @Datetime, @Links, @Content,     @Subject)";
        cmd.Parameters.Add("@Device", System.Data.SqlDbType.NVarChar).Value = Device;
        cmd.Parameters.Add("@Source", System.Data.SqlDbType.NVarChar).Value = Source;
        cmd.Parameters.Add("@Reviewer", System.Data.SqlDbType.NVarChar).Value =     Reviewer;
        cmd.Parameters.Add("@Datetime", System.Data.SqlDbType.Date).Value = Datetime;
        cmd.Parameters.Add("@Links", System.Data.SqlDbType.NVarChar).Value = Links;
        cmd.Parameters.Add("@Content", System.Data.SqlDbType.NVarChar).Value = Content;
        cmd.Parameters.Add("@Subject", System.Data.SqlDbType.NVarChar).Value = Subject;
        cmd.CommandType = System.Data.CommandType.Text;
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();

   }
}

我意识到当我只能从FileUpload读取内容时,有一个连接是有点无意义的,但是如果有人知道我做错了什么或者可以指导一个非常值得赞赏的正确方向。谢谢你的时间

1 个答案:

答案 0 :(得分:0)

好吧,我想我认为那些瞄准同样事情的人......首先是你的事情

  • 我正在导入.CSV文件,因此您的连接字符串将与大多数Excel连接字符串不同

  • 其次,确保你处理你的文件cuz,即使它已关闭,也会为你提供正在使用的文件的问题,但是如果它打开它会崩溃(我还没有处理过那部分代码)

  • 第三,如果您将数据导入数据库,请确保您的数据类型正确。例如,我有大量数据即将进行,因此我必须将我的数据类型更改为正确的格式。< / p>

标记:

<asp:FileUpload ID="FileUpload1" runat="server" />
       <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
              <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
                       <asp:Label ID="Label1" runat="server"></asp:Label>

这里做得不多,只是基本的控制

C#代码背后:

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)   //Upload file here
        {

            string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);  //Get extension

            if (fileExt == ".csv")   //check to see if its a .csv file
            {

                FileUpload1.SaveAs("C:\\FolderName\\" + FileUpload1.FileName);        //save file to the specified folder
                OleDbConnection oconn = new     OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\AudioPRFiles\\; Extended     Properties='text; HDR=Yes; FMT=Delimited'");   //string connection for .CSV     OR Text file

                try
                {
                    OleDbCommand ocmd = new OleDbCommand("SELECT * FROM [" +     FileUpload1.FileName + "]", oconn);    //Select statement, if your using .CSV...put the name of the file NOT the excel tab


                oconn.Open();

                OleDbDataReader odr = ocmd.ExecuteReader();  


                string Device = "";
                string Source = "";
                string Reviewer = "";
                string Datetime = "";
                string Links = "";
                string Content = "";
                string Subject = "";

                while(odr.Read())

                {

                    Device = valid(odr, 0);     //Call the valid method...see below
                    Source = valid(odr, 1);
                    Reviewer = valid(odr, 2);
                    Datetime = valid(odr, 3);
                    Links = valid(odr, 4);
                    Content = valid(odr, 5);
                    Subject = valid(odr, 6);

                    InsertDataIntoSql(Device, Source, Reviewer, Datetime, Links, Content, Subject);  //Call the InsertDataIntoSql method...see below

                    FileUpload1.Dispose();  //Dispose the file


                }

                oconn.Close();   //Close connection

            }

            catch (Exception ee)
            {
                Label1.Text = ee.Message;
                Label1.ForeColor = System.Drawing.Color.Red;
            }
            finally
            {
                Label1.Text = "Data Inserted Successfully";
                Label1.ForeColor = System.Drawing.Color.Green;

            }

        }

        else
        {
            Label1.Text = "Only .csv files allowed!";

        }

    }

    else
    {

        Label1.Text = "You have not specified a file!";

    }    
 }



protected string valid(OleDbDataReader myreader, int stval)  //this method checks for null values in the .CSV file, if there are null replace them with 0

{
    object val = myreader[stval];
    if (val != DBNull.Value)
    {

        return val.ToString();
    }
    else
    {
        return Convert.ToString(0);
    }


}

public void InsertDataIntoSql(string Device, string Source, string Reviewer, string Datetime, string Links, string Content, string Subject) //method to insert data into database

{
    SqlConnection conn = new SqlConnection("Server=ServerAddress; Database=MyDatabaseName; Trusted_Connection=True");                        //SQL connection
    SqlCommand cmd = new SqlCommand();                           //SQL command
    cmd.Connection = conn;
    cmd.CommandText = "USE [MyDataBase] INSERT INTO Table_Name(Device, Source, Reviewer, Datetime, Links, Content, Subject) VALUES(@Device, @Source, @Reviewer, @Datetime, @Links, @Content, @Subject)";
    cmd.Parameters.Add("@Device", System.Data.SqlDbType.Int).Value = Device;
    cmd.Parameters.Add("@Source", System.Data.SqlDbType.NVarChar).Value = Source;
    cmd.Parameters.Add("@Reviewer", System.Data.SqlDbType.NVarChar).Value = Reviewer;
    cmd.Parameters.Add("@Datetime", System.Data.SqlDbType.Date).Value = Datetime;
    cmd.Parameters.Add("@Links", System.Data.SqlDbType.NVarChar).Value = Links;
    cmd.Parameters.Add("@Content", System.Data.SqlDbType.NVarChar).Value = Content;
    cmd.Parameters.Add("@Subject", System.Data.SqlDbType.NVarChar).Value = Subject;
    cmd.CommandType = System.Data.CommandType.Text;
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

   }
}

Hope this helps..Thanks