[英]How do I open access database in C# using a file path from a command line argument?
I need to specify the file path of an access db as a command line argument and pass it to my C# program, which will open and perform operation on it. 我需要将访问数据库的文件路径指定为命令行参数,并将其传递给我的C#程序,该程序将打开并对其执行操作。
In the Command Prompt I type F:\\\\count
which I should able to access using args[0], but I get Invalid value for key 'data source'
exception. 在命令提示符中,我键入
F:\\\\count
,我应该使用args [0]来访问,但是我获得Invalid value for key 'data source'
异常的Invalid value for key 'data source'
。
When I put the same path in the code as string path = "F:\\\\count"
then it works. 当我在代码中使用相同的路径作为
string path = "F:\\\\count"
然后它工作。
Please tell me what I'm doing wrong! 请告诉我我做错了什么! I'm lost.
我迷路了。
Here is my code: 这是我的代码:
namespace CountProjectPages
{
public class CountProjectPages
{
private static OleDbConnection myConnection;
static void Main(string[] args)
{
try
{
string path = args[0];
AppDomain.CurrentDomain.SetData("DataDirectory",path);
myConnection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=|DataDirectory|\\test.mdb;Jet OLEDB:Database Password=aaa");
string myScalarQuery = "SELECT COUNT (Content.Page) from Content";
OleDbCommand myCommand = new OleDbCommand(myScalarQuery, myConnection);
myConnection.Open();
int total = (Int32)myCommand.ExecuteScalar();
Console.WriteLine(total);
Console.WriteLine("DataSource: {0}",myConnection.DataSource);
}
catch (Exception ex)
{
Console.WriteLine("Ex: " + ex);
}
finally
{
myConnection.Close();
}
}
}
}
In response to your question 回答你的问题
do you think that it's possible to pass the file name (eg test.mdb) as a command line argument too?
你认为可以将文件名(例如test.mdb)作为命令行参数传递吗?
How to use command-line switches in Microsoft Access 如何在Microsoft Access中使用命令行开关
Check this code: 检查此代码:
static void Main(string[] args)
{
string dbPath = null;
if (args.Length > 0)
{
dbPath = args[0];
string connectionString = "PROVIDER=MICROSOFT.JET.OLEDB.4.0;DATA SOURCE=" + dbPath + ";";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
//TODO: handle other db commands...
}
}
}
Make sure that command argument is passed as complete or relative path to mdb file using quotes like this: "f:\\some directory\\MyDataBase.mdb" 确保使用如下引号将命令参数作为mdb文件的完整路径或相对路径传递:“f:\\ some directory \\ MyDataBase.mdb”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.