gpt4 book ai didi

c# - C#Windows Form应用程序中的连接字符串错误

转载 作者:行者123 更新时间:2023-12-03 09:03:14 24 4
gpt4 key购买 nike

我是C#的新手,目前正在学习Windows窗体。连接到本地数据库时,出现关于连接字符串的错误。我收到的错误是Sql在以下行中-

public Form1()
{
InitializeComponent();
con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="c: \users\devesh lashkari\documents\visual studio 2015\Projects\DemoApp1.0\DemoApp1.0\DemoAppDataBase.mdf";Integrated Security=True");
}

在这里,文件名出现错误。我已经附上了一个截图,以便于检测。

enter image description here

最佳答案

您有两种选择:

逃避一切

尝试以下方法:

    con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;" +
"AttachDbFilename=\"c:\\users\\devesh lashkari\\documents\\visual studio 2015\\Projects\\DemoApp1.0\DemoApp1.0\\DemoAppDataBase.mdf\";" +
"Integrated Security=True");

双引号

...或者如果您想使用 @,则需要使用 GalacticCowboy(如下)所述的双引号:
    con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""c:\users\devesh lashkari\documents\visual studio 2015\Projects\DemoApp1.0\DemoApp1.0\DemoAppDataBase.mdf"";Integrated Security=True");

注意,与其说是SQL错误,不如说是C#转义错误。您需要在路径中加引号,以便不能使用 @。我将其分为多行以使其更易于阅读。

另外在 c:后还有一个空格

感谢 GalacticCowboy的提示和发现我的愚蠢。 ;)

关于c# - C#Windows Form应用程序中的连接字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47367067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com