簡體   English   中英

嘗試連接到C#中用於項目的Access數據庫時出錯

[英]Error when trying to connect to access database in C# for project

我正在嘗試創建一個項目,該項目將讀取,寫入和檢查訪問數據庫文件中的重復項。 我正在使用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");
            }
        }

    }

`

您尚未打開連接。

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);
    }
}

這樣可以確保關閉連接並釋放資源。

請嘗試按照以下示例操作: https : //msdn.microsoft.com/zh-cn/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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM