尝试连接到C#for project中的access数据库时出错
我正在尝试创建一个项目,该项目将读取、写入和检查access数据库文件中的重复项。我正在使用C#并不断收到“连接失败错误”,如果连接状态为0,我会将该错误写入程序。如果有人能提供任何帮助,我将不胜感激。我正在使用Access 2016,我不确定我的项目需要什么样的参考资料(如果有)。我在网上找到的所有内容都过时或不起作用 谢谢大家!尝试连接到C#for project中的access数据库时出错,c#,.net,ms-access-2016,C#,.net,Ms Access 2016,我正在尝试创建一个项目,该项目将读取、写入和检查access数据库文件中的重复项。我正在使用C#并不断收到“连接失败错误”,如果连接状态为0,我会将该错误写入程序。如果有人能提供任何帮助,我将不胜感激。我正在使用Access 2016,我不确定我的项目需要什么样的参考资料(如果有)。我在网上找到的所有内容都过时或不起作用 谢谢大家! using System; using System.Collections.Generic; using System.ComponentModel; using
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 (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.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.
你在哪里打开连接?你有没有看一看你没有打开连接。试过了,还是没有连接异常怎么说?我已经更新了原始问题中的代码,因为我不知道如何在这里发布它。我没有得到异常你怎么知道它不起作用?如果你是消息
“连接失败“
,然后您得到了一个您接受的异常。尝试将ex.Message
添加到您的邮件中,如我在我的anwser中所示。您不应该替换原来的问题,因为这会使针对这一点给出的所有评论和答案无效。不过,欢迎你为问题补充更多信息,我深表歉意。我已将代码更新到您的规格,并收到错误“unrecognized database format”,不知道原因。我像5次一样重新创建了该文件谢谢,我已经发布了更新的代码,仍然无法工作。肯定是我的错