首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# oledbexception

C# oledbexception
EN

Stack Overflow用户
提问于 2012-04-05 20:58:42
回答 1查看 2.7K关注 0票数 3

我正在进行一个C#项目,将excel文件中的数据读入Access数据库。我一直得到一个OleDbException类型的例外。现在的问题不是为什么我会有这个错误,而是如何处理它。我得到了错误,因为我让用户决定他们想上传哪个文件,有些文件可能没有正确的标题或格式。下面是我使用的代码:

**行是抛出异常的原因。我试过使用:

  1. catch (OleDbException)
  2. catch {}
  3. catch (Exception)

但是,异常似乎从未抛到我的catch子句中。

代码语言:javascript
复制
public UploadGrades(string filename, OleDbConnection con)
{
    this.filename = filename;
    this.con = con;
    //connect to the file and retrive all data.
    excelconn = new OleDbConnection(
     @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"");;
   
    try
    {
        excelconn.Open();
        OleDbCommand command = new OleDbCommand("SELECT temp, name, score, submitdate, test from [sheet1$]", excelconn);
        **reader = command.ExecuteReader();**
    }
    catch 
    {
        MessageBox.Show("The File " + filename + " cann't be read.  It is either in use by a different user \n or it doen't contain the " +
            "correct columns.  Please ensure that column A1 is temp B1 is Name C1 is Score D1 is Submitdate and E1 is Test.");
    }
 }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-05 21:15:55

这可能是连接字符串的问题,或者您没有安装ACE.OLEDB库,因此OleDB无法找到正确的提供程序。查看这个可选连接字符串页面,否则您应该可以从这里下载提供程序。

您可能需要尝试以下几种方法:

代码语言:javascript
复制
try
{

       using(OleDbConnection excelConnection = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"", filename)))
       {
        excelConnection .Open();     
          using(OleDbCommand command = new OleDbCommand("SELECT columbia_uni, name, score, submitdate, test from [sheet1$]", excelconn))
          {     
                 command.CommandType = CommandType.Text;
                 using(IDataReader reader = command.ExecuteReader())
                 {
                    while(reader.Read())
                    {
                      //Do something
                    }
                 }    
          }
       }


}
catch(Exception e)
{
    MessageBox.Show("The File " + filename + " cann't be read.  It is either in use by a different user \n or it doen't contain the correct columns.  Please ensure that column A1 is Columbia_UNI B1 is Name C1 is Score D1 is Submitdate and E1 is Test.\r\n The actual exception message is: " + e.Message);
}

使用相当于尝试/最后,并将确保适当地清除连接、命令和IDataReader对象。catch块应该捕获(几乎)由此代码生成的任何异常。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10035927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档