【问题标题】:Import data to database using c#使用c#将数据导入数据库
【发布时间】:2014-05-19 06:05:39
【问题描述】:

我有一个包含 1000 行的 gridview,我还有一个导出和导入功能。例如。当我导出 100 行并对它们进行更改并再次导入它们时,只会反映更改的 100 行。其余更改的行保持不变。

我正在使用下面的代码将数据导入数据库。现在如何在此工作模型之上导入时添加新行。

非常感谢任何指导。

代码:

protected void btnImportXL_Click(object sender, EventArgs e)
{
    string strSqlTable = "##TempupdatePm";
    string sexcelconnectionstring = "";
    string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower();
    // string path = FileUploadExcel.PostedFile.FileName;
    string query = "";

    string FileName = string.Empty;
    //GridView2.Visible = false;
    FileName = Path.GetFileName(FileUploadExcel.PostedFile.FileName);
    string Extension = Path.GetExtension(FileUploadExcel.PostedFile.FileName);
    string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
    //  string path = FileName;

    //Get file name of selected file     
    string path = Path.GetFileName(Server.MapPath(FileUploadExcel.FileName));
    System.IO.File.Delete(Server.MapPath(FolderPath) + path);
    //Save selected file into server location         
    FileUploadExcel.SaveAs(Server.MapPath(FolderPath) + path);
    //Get file path     
    string filePath = Server.MapPath(FolderPath) + path;

    if (strFileType != String.Empty)
    {
        //Connection String to Excel Workbook
        if (strFileType.Trim() == ".xls")
        {
            sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
        }
        else if (strFileType.Trim() == ".xlsx")
        {
            sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please upload the correct file format')", true);
            return;
        }
        try
        {
            OleDbConnection conn = new OleDbConnection(sexcelconnectionstring);
            if (conn.State == ConnectionState.Closed)
                conn.Open();

            System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string sheetname = dt.Rows[0]["Table_Name"].ToString();
            query = "SELECT * FROM [" + sheetname + "]";
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
            oledbconn.Open();
            OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn);
            OleDbDataReader dReader;
            dReader = oledbcmd.ExecuteReader();
            string create1 = "Create Table " + strSqlTable + "( [CODE] [varchar](10) NOT NULL,[Name] [varchar](150) NOT NULL,[Group] [varchar](10) NOT NULL,  [Team] [varchar](10) NOT NULL, [Size1] [varchar](10) NOT NULL, [Size2] [varchar](10) NOT NULL";

            SqlConnection sqlconn2 = new SqlConnection(strConnectionString);
            SqlCommand sqlcmd2 = new SqlCommand(create1, sqlconn2);
            sqlconn2.Open();
            sqlcmd2.ExecuteNonQuery();

            SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlconn2);
            sqlBulk.DestinationTableName = strSqlTable;
            sqlBulk.WriteToServer(dReader);



            string update1 = "update o set o.Size1=t.Size1,O.Size2=t.Size2 from  Application as o inner join ##TempupdatePm as t on(o.CODE=t.CODE )and (o.Team=t.Team) and (o.Group=t.Group) where (o.CODE=t.CODE ) and (o.Group=t.Group)";
            SqlCommand sqlcmd1 = new SqlCommand(update1, sqlconn2);
            sqlcmd1.ExecuteNonQuery();

            string drop1 = "drop Table " + strSqlTable;
            SqlCommand sqlcmd3 = new SqlCommand(drop1, sqlconn2);
            sqlcmd3.ExecuteNonQuery();
            oledbconn.Close();
            conn.Close();
            conn.Dispose();
            sqlconn2.Close();
            ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Data saved successfully');window.location='ApplicationInfo.aspx';", true);
        }

        catch (Exception ex)
        {

        }

        //objDA.BindGrid(GridView1, "select * from " + strSqlTable);
    }
    else
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true);
    }
}

【问题讨论】:

  • 您想知道如何在更新时导入到 sql 吗?
  • @Jonny - 是的。在此更新之上,我可能希望在导入时添加新行,这些行当前不在现有表中。
  • 我看到你对你想要做什么有一个想法,我认为在我帮助你之前,试着做一个 sql 语句来满足所有人的需求。你需要有一个如果不存在的语句来插入和一个更新如果存在:)应该满足它:)
  • @Jonny - 你可以帮助我编写场景的代码吗?
  • 我能做到 :) 给我几分钟时间写点东西

标签: c# asp.net .net gridview


【解决方案1】:

用你的 sql 查询做这样的事情,用一个查询插入和更新。

INSERT INTO MyTable (field1, field2, fieldN)
VALUES ("value1","value2", "valueN")
ON DUPLICATE KEY UPDATE 
field1=VALUES(value1)
field2=VALUES(value2)
fieldN=VALUES(valueN)
//and so on. 

【讨论】:

  • 既然 sql server 不支持这种语法,你怎么做呢?
【解决方案2】:

你可以在更新之前写一个插入语句

Insert in to table select CODE,Size1,Size2 from #temp_table where CODE not in (Select code from table ) 

然后像以前一样继续。

【讨论】:

  • 曾经投过反对票的人,请解释一下这个答案有什么问题。
  • 是我。我的意思是点击投票,但有一个计时器限制我投票。 :) 会稍微改变一下
  • 你能编辑你的分析器吗,请在某处放一个冒号
  • insert into Application Info select Code, Name, Group, Team, Size1, Size2 from ##TempupdatePm where code not in (select code, Name, Group, Team) from Application Info //但有查询形成问题。请建议。 Error:Incorrect syntax near the keyword 'from'.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
相关资源
最近更新 更多