嘿,我是编程新手,从未制作过需要在另一台电脑上工作的实际程序。该程序与数据库连接。当我在另一台电脑上时,我更改了program.exe.config文件,以便我可以应用数据库的正确位置,但它仍然无法正常工作。这是我的代码,也许这里有问题。 的app.config:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
标准代码中的:
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb");
答案 0 :(得分:0)
首先,您要在应用程序配置文件中指定连接字符串:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
您没有使用 Program.exe.config 中的连接字符串,而是复制并粘贴连接字符串。
如果你稍微改变你的代码,也许你可以看到我的意思:
//Get the connection string to use
String connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb";
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
您应该做的是从应用程序的配置中提取连接字符串:
//Get our connection string setting, and the connectionString it contains
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
String connectionString = cs.ConnectionString;
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
您还可以进行一项更改。您的连接字符串条目本身指定您要使用的提供程序:
providerName="System.Data.OleDb"
然后你继续自己使用该提供者:
OleDbConnection con = new OleDbConnection(...);
如果您更改了连接字符串以使用其他提供程序:
providerName="System.Data.SqlClient"
您的代码仍将使用 OleDbConnection ,而不是应用程序配置中提供的提供程序。
幸运的是,.NET框架有一个方便的小助手功能,可以为创建正确的提供者:
public static DbConnection GetConnection()
{
//Get the connection string info from our application config
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
if (cs == null)
throw new Exception("Could not find connection string settings");
//Get the factory for the given provider (e.g. "System.Data.OleDbClient")
DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName);
if (factory == null)
throw new Exception("Could not obtain factory for provider \"" + cs.ProviderName + "\"");
//Have the factory give us the right connection object
DbConnection conn = factory.CreateConnection();
if (conn == null)
throw new Exception("Could not obtain connection from factory");
//Knowing the connection string, open the connection
conn.ConnectionString = cs.ConnectionString;
conn.Open();
return conn;
}