上传文件到SQL Server [英] Uploading a file into SQL Server

查看:164
本文介绍了上传文件到SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换个字眼的问题......下面code中的数据插入到一个SQL Server数据库,并进入然而正确的表,将数据插入不正确......这里是code

Reword the question... the below code inserts the data into an SQL Server database, and into the correct table however, the data is not inserted correctly... here is the code

if (FileUpload1.HasFile)
{
    string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
    FileUpload1.PostedFile.SaveAs(path);

    OleDbConnection OleDbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";");
    OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", OleDbcon);
    OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);

    OleDbcon.Open();

    DbDataReader dr = cmd.ExecuteReader();
    string con_str = @"Data Source=ENERGYSQL\ENERGY;Initial Catalog=ProjectHandler;Persist Security Info=True;User ID=aconyon;Password=birchall";

    SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
    bulkInsert.DestinationTableName = "StockTable";
    bulkInsert.WriteToServer(dr);

    OleDbcon.Close();

    Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
    //Label1.ForeColor = Color.Green;
    Label1.Text = "Successfully inserted";
}
else
{
    //Label1.ForeColor = ConsoleColor.Red;
    Label1.Text = "please select ther File";
}

这是什么code的作用是选择远远最右边一栏,在我的例子数量,只是插入到数据库中这一点,忽略所有其它行(A和B)我需要改变的OleDbCommand选择某些行。 A(ITEMNAME),B(日期),C(数量)

what this code does is select the far most right column, in my example Quantity, and insert just this into the database, ignoring all other rows (A and B) do i need to change the OleDbCommand to select certain rows. A(ItemName), B(Date), C(Quantity)

推荐答案

使用code。

string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'", 
Server.MapPath(@"~\DownloadedExcelFilesOp4\myfile" + fileExt));// + "\\" +
FileUploadControl.PostedFile.FileName.ToString());
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
   OleDbCommand command = new OleDbCommand(("Select [Demo1] ,[Demo2]  FROM [Sheet1$]"), 
   connection);
   connection.Open();
   using (DbDataReader dr = command.ExecuteReader())
   {
   }
}

这篇关于上传文件到SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆