我在winforms C#中将exceldb文件上传到sql server时遇到了麻烦
本文关键字:server sql 遇到 麻烦 winforms 中将 exceldb 文件 我在 | 更新日期: 2024-09-27 08:06:28
我正在尝试创建一个Excel数据上传器,以便使用C#中的Winforms将Excel文件上传到SQL Server。
在bulkcopy.WriteToServer(dr);
之后,我得到了这个错误:
多步骤OLE DB操作生成错误。检查每个OLE DB状态值(如果可用)。没有完成任何工作
用于查看链接的Microsoft Excel工作表的连接已丢失。
我在这里得到了关于regedit的信息,并试图遵循它,但仍然出现了相同的错误:
class Pass
{
static string _excelfilepath;
public static string excelfilepath { get { return _excelfilepath; } set { _excelfilepath = value; } }
public void importdatafromexcel()
{
//declare variables - edit these based on your particular situation
string ssqltable = "tStudent";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select idnum,fname,gname,mname,coacro,year,yrstat,sex,stat,telno,addr1,addr2,addr3,dbirth,mothname,fathname,civstat,religion,hssch from [masterlist$]";
try
{
//create our connection strings
string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + _excelfilepath +
";extended properties=" + "'"excel 8.0;hdr=yes;'"";
string ssqlconnectionstring = @"Data Source=LYNDON-PC'LYNDON;Initial Catalog=trial;Persist Security Info=True;User ID=sa;Password=14323531";
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
这个错误意味着什么,并获取将Excel文件上传到SQL Server数据库中的表的代码。。。
我认为你应该使用
bulkcopy.WriteToServer(dr);
而不是使用
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}