如何解决OleDbConnection错误-使用动态文件路径问题
我无法动态获取MS Access数据库的文件路径。我在搞乱它的硬编码,但似乎无法使其动态工作。我关注了其他一些论坛/文档,但无法让它们为我工作。我发现有几对与我的问题很接近。
OleDbConnection Source Variable in C# https://docs.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbconnection.connectionstring?view=dotnet-plat-ext-3.1
错误是:
这是我的代码:
public partial class testForm : Form
{
public OleDbConnection connOp = new OleDbConnection();
//public string filePath = connOp.DataSource; //<---Doesnt work unless connOp variable is static.
//But,ConnectionString with filePath in arguments doesnt work still.
public testForm()
{
InitializeComponent();
connOp.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\cscox\AppData\Roaming\Autodesk\AutoCAD Electrical 2021\R24.0\enu\Support\User\SAMPLE.mdb;Persist Security Info=False;"; // #1 - Works but not Dynamic
//connOp.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=(local);Persist Security Info=False;"; //#2 - Doesnt work
//connOp.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + connOp.DataSource + ";Persist Security Info=False;"; //#3 - Doesnt work,was my first attempt at solution
//connOp = new OleDbConnection(String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;",filePath)); // #4 - Doesnt work,used with static connOp variable ahead
}
private void btnAccess_Click(object sender,EventArgs e)
{
try
{
connOp.Open();
testLabelAccess.Text = "Connection Successful";
MessageBox.Show(connOp.DataSource);
//OleDbCommand cmd = new OleDbCommand();
//cmd.Connection = conn;
connOp.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。