-2

我有一个包含评论的 .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 中读取内容时,建立连接有点毫无意义,但是如果有人知道我做错了什么或者可以指导正确的方向,我将不胜感激。谢谢你的时间

4

1 回答 1

0

好吧,我想我是为那些追求与我相同的目标的人想出来的……首先要做几件事

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

  • 其次,确保你处理你的文件,因为即使文件关闭,它也会给你使用中的文件带来问题,但如果它打开它会崩溃(我还没有处理那部分代码)

  • 第三,如果您将数据导入数据库,请确保您的数据类型是正确的..例如,我有很多数据来了,并且正在被处理,所以我不得不将我的数据类型更改为正确的格式。

标记:

<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
于 2012-05-04T13:46:13.530 回答