如何在连接字符串中使用变量?

时间:2017-03-07 03:14:39

标签: c# vb.net .net-3.5

我遇到连接字符串变量的问题。在我的app.config数据库路径似乎很好,但在窗体上,我收到该连接字符串的错误。当我尝试添加:

_connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; " +
    "AttachDbFilename = \"|DataDirectory|\\gazi_db.mdf\"; " +
    "Integrated Security = True; Connect Timeout = 30";

数据库无法正常工作;退出时无法保存数据。但是这很好用:

connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; " +
        "AttachDbFilename = \"C:\\Users\\Can\\Desktop\\c_sharp_gazi_installer" +
        "\\Gazi Installer\\gazi_installer\\gazi_db.mdf\"; " +
        "Integrated Security = True; Connect Timeout = 30";

我该如何解决这个问题?

编辑:我希望这会有用

string DataDirectory = "";
string folder = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().CodeBase);
AppDomain.CurrentDomain.SetData("DataDirectory", folder);

_connectionString = _connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; " +
        "AttachDbFilename = \"" + DataDirectory + "\\gazi_db.mdf\"; " +
        "Integrated Security = True; Connect Timeout = 30";

但它仍然给我sqlclient sqlexception错误。

EDIT2:此错误表示连接已打开。我不明白为什么这也不起作用:

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Data Source"] = "(LocalDB)\\MSSQLLocalDB";
builder["AttachDbFilename"] = @"C:\Users\Can\\Desktop\c_sharp_gazi_installer\Gazi Installer\gazi_installer\gazi_db.mdf";
builder["Integrated Security"] = true;
builder["Connect Timeout"] = 30;

请有人帮忙。我要发疯了。

2 个答案:

答案 0 :(得分:2)

首先,您可以使用@"符号"避免使用这么多的转义字符。 那么,你在哪里定义了" DataDirectory"变量?

答案 1 :(得分:1)

.NET有一个connection string builder类。使用此方法,您可以将每个值(即数据源,集成安全性)分别设置为变量,然后使用.ConnectionString属性获取连接字符串。