【问题标题】:How do I connect to an MDF database file?如何连接到 MDF 数据库文件?
【发布时间】:2012-02-14 03:20:19
【问题描述】:

我第一次尝试将 C# 应用程序连接到 MDF 数据库,我需要一些帮助..

我在 Visual Studio 2010 中制作了一个小型 MDF 数据库文件,然后创建了另一个项目并将该文件导入到项目本身中。

我没有尝试通过代码连接到 MDF 文件。这是我正在使用的代码:

namespace DBtestApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.Data.SqlClient.SqlConnection con;
        private void Form1_Load(object sender, EventArgs e)
        {
            con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = "DataSource=.\\SQLEXPRESS; AttachDbFilename =SampleDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            con.Open();
            MessageBox.Show("Connection opened");
            con.Close();
            MessageBox.Show("Connection closed");
        }
    }
}

当我运行应用程序时,我在定义连接字符串的那一行得到一个异常,并且异常在堆栈顶部有这条消息:

System.ArgumentException: Keyword not supported: 'datasource'.

有人能指出我正确的方向吗?

【问题讨论】:

  • 这篇文章可能会有所帮助:[如何在一个简单的 Web 项目中连接到 .mdf(Microsoft SQL Server 数据库文件)?][1] Cheerz [1]:stackoverflow.com/questions/173209/…

标签: c# sql database visual-studio-2010


【解决方案1】:

在Data Source之间添加空格

 con.ConnectionString = @"Data Source=.\SQLEXPRESS;
                          AttachDbFilename=c:\folder\SampleDatabase.mdf;
                          Integrated Security=True;
                          Connect Timeout=30;
                          User Instance=True";

【讨论】:

  • 在编辑时,删除; AttachDbFilename =中的空格
  • 试过了,但现在我得到了以下异常:System.Data.SqlClient.SqlException (0x80131904): An attempt to attach an auto-named database for file SampleDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
  • 需要指定sampleDatabase.mdf的路径。看看编辑过的帖子。
  • 但是当我已经将MDF文件添加到项目的本地资源时,为什么还要指定完整路径呢? .. 我不想硬编码路径,因为这意味着 MDF 文件必须始终存在.. 我可以不引用它在项目中的本地存在吗?
  • 我正在考虑编辑它,以便将字符串连接起来以消除水平滚动,但恐怕我对此了解不够,无法相信自己不会让答案不正确。
【解决方案2】:

转到服务器资源管理器 > 您的数据库 > 右键单击​​ > 属性 > ConnectionString 并复制连接字符串并将复制到的连接字符串代码过去:)

【讨论】:

  • 迄今为止我见过的最好的答案之一 :)
  • 这将在您在另一台机器上尝试时中断。虽然该连接字符串对您的机器有效,但如果您花一点时间阅读它,您会注意到它的路径是硬编码的。
【解决方案3】:
string sqlCon = @"Data Source=.\SQLEXPRESS;" +
                @"AttachDbFilename=|DataDirectory|\SampleDB.mdf;
                Integrated Security=True;
                Connect Timeout=30;
                User Instance=True";
SqlConnection Con = new SqlConnection(sqlCon);

文件路径应该有|DataDirectory|,它实际上链接到“当前项目目录\App_Data\”或“当前项目目录”并获取.mdf文件.....放置.mdf在这些地方中的任何一个并且应该在visual studio 2010中工作。当您在生产系统上使用独立应用程序时,可执行文件所在的当前路径应该有.mdf文件。

【讨论】:

    【解决方案4】:

    对于 Visual Studio 2015,连接字符串是:

    "Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True"
    

    【讨论】:

    • 这是唯一对我有用的 MDF。我正在使用 .Net Core 3 的 VS2019。
    【解决方案5】:
    Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
    

    【讨论】:

    • 我试过这个修改版""Server=.\\SQLExpress;AttachDbFilename=SampleDatabase.mdf;Database=SampleDatabase; Trusted_Connection=Yes",得到了如下异常:System.Data.SqlClient.SqlException (0x80131904): A file activation error occurred. The physical file name 'SampleDatabase.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. Cannot attach the file 'SampleDatabase.mdf' as database 'SampleDatabase'.
    【解决方案6】:

    替代解决方案,您可以将数据库放在解决方案中所需的文件夹中。这对我有用:

    .ConnectionString(@"Data Source=(LocalDB)\MSSQLLocalDB;
                        AttachDbFilename="+AppDomain.CurrentDomain.BaseDirectory+"Folder1\\Folder2\\SampleDatabase.mdf" + ";
                        Integrated Security=True;")
    

    【讨论】:

      【解决方案7】:
      SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Samples\MyApp\C#\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
      

      这对我有用...有什么办法可以缩短路径吗?喜欢

      SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多