【问题标题】:Error when trying to connect to access database in C# for project尝试在 C# 中为项目连接访问数据库时出错
【发布时间】:2018-01-25 20:26:45
【问题描述】:

我正在尝试创建一个项目,该项目将读取、写入和检查我的访问数据库文件中的重复项。我正在使用 C# 并不断收到“如果连接状态 = 0,我已写入程序的连接失败错误。如果有人能提供任何帮助,我将不胜感激。我正在使用 Access 2016,但我不确定我需要哪些参考资料用于我的项目(如果有的话)。我在网上找到的所有东西要么已经过时,要么不起作用。

谢谢!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;
using System.Data.OleDb;


 namespace RHG
{

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb"))
        {
            try
            {
                connection.Open();
                MessageBox.Show("connected");
            }
            catch (Exception ex)
            {
                MessageBox.Show("connection failed");
            }
        }

    }

`

【问题讨论】:

标签: c# .net ms-access-2016


【解决方案1】:

你还没有打开连接。

connection.Open();

注意:检查连接状态是不够的。尝试打开连接时可能会出现异常。而是将其包含在 try-catch 中。

将工作与using 关联起来也是一个好习惯

using (var connection = new OleDbConnection()) {
    connection.ConnectionString =
        @"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\...\Used.accdb";
    try {
        connection.Open();

        //TODO: do something with the connection

    } catch (Exception ex) {
        MessageBox.Show("Connection Failed\r\n\r\n" + ex.Message);
    }
}

这样可以确保关闭连接并释放资源。

【讨论】:

  • 试过了,还是连接不上
  • 异常说明了什么?
  • 我已经更新了原始问题中的代码,因为我不知道如何在此处发布它。我没有遇到异常
  • 你怎么知道它当时没有用?如果您收到消息"connection failed",那么您收到了一个您吞下的异常。尝试将 ex.Message 添加到您的消息中,正如我在我的 anwser 中显示的那样。您不应该替换原始问题,因为这会使该点给出的所有 cmets 和答案无效。但是,欢迎您在问题中添加其他信息。
  • 我很抱歉。我已将代码更新为您的规范,并且收到错误“无法识别的数据库格式”,不知道为什么。我重新创建了 5 次文件
【解决方案2】:

尝试按照此处的示例进行操作:https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection(v=vs.110).aspx

您缺少连接。Open();语句,应该包含在 try catch 中。

另外,你可以在构造函数中指定连接字符串,比如

using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb")) 
{
    //do DB access here
}
//no need to call connection.Close() - it's automatically done once you leave the using block.

【讨论】:

  • 谢谢,我已经发布了更新的代码,但仍然无法正常工作。我确定这绝对是我的错
猜你喜欢
  • 2014-06-09
  • 2018-10-15
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2020-09-05
  • 2014-04-29
相关资源
最近更新 更多