【问题标题】:Connect to an MDF Database连接到 MDF 数据库
【发布时间】:2015-01-20 17:05:32
【问题描述】:

在 Visual Studio Form 中,我正在创建一个 c# 应用程序。我试图将输入到注册表中的数据添加到我用表格创建的 MDF 数据库文件中。但是我无法连接到数据库,有什么帮助吗?

点击时我的注册按钮代码

private void CreateAccBtn_Click(object sender, EventArgs e)
{
    string ConnectToDatabase = ("Data Source=  (LocalDB)\v11.0;AttachDbFilename=E:\\Work\\Information Systems      Development\\Game\\My Brain Cognitive Game\\My Brain Cognitive Game\\Brain Game Database.mdf;Integrated Security=True;Connect Timeout=10");
    SqlConnection ConnectDatabase = new SqlConnection(ConnectToDatabase);
    SqlCommand CMDDatabase = new SqlCommand("Insert Into Brain Game Database.User Table (User Name, Date Of Birth, Gender, Date Account Created, Condition, Email, Password) values('" + this.NewUsernameTxtBox.Text + "','" + this.DOBDateTimePicker3.Text + "','" + this.SexListBox1.Text + "','" + this.CurrentDatePicker1.Text + "','" + this.NewConditionTxtBox.Text + "','" + this.NewEmailTxtBox.Text + "','" + this.NewPasswordTxtBox.Text + "');",ConnectDatabase);
    SqlDataReader MyReader;
    try
    {
         ConnectDatabase.Open();
         MyReader = CMDDatabase.ExecuteReader();
         MessageBox.Show("Account Created");
         while (MyReader.Read())
         {

         }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}  

【问题讨论】:

  • But i cant connect to the database 这是什么意思?你得到什么错误信息?你在这里问之前做过什么研究?几乎您可能收到的每条错误消息都已被多次回答和解释。那么是什么让您决定创建一个新问题的具体案例?
  • C# ConnectionStrings For Databases 也可以将文件放在较短的文件路径中,只是对这些空格感到好奇AttachDbFilename=E:\\Work\\Information Systems Development\\Game\\My Brain Cognitive Game\\My Brain Cognitive Game\\Brain Game Database.mdf; 我建议在 @ 文字前添加
  • 它只是说“建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。(提供程序:命名管道提供程序,错误:40 - 无法打开与 SQL Server 的连接)

标签: c# visual-studio-2010 sqlconnection mdf


【解决方案1】:

有一些事情可以帮助您建立联系。这周我刚刚帮助几个学生完成了他们的联系。

请仔细检查您的连接字符串是否正确(指向正确的位置 - .MDF 文件的路径)

  1. 确保连接字符串正确。
  2. 尽量不要在您的项目中使用重复的数据库。
  3. 确保所有设置中的数据库路径都正确(此处存在重复的数据库可能会让您感到困惑)
  4. 添加新连接时,有一个Test Connection 按钮。在尝试从代码执行查询之前,请单击它并确保连接正常。
  5. 一切完成后,先使用Select * FROM tblName查询语句进行测试,而不是使用更容易出现拼写错误的插入语句。

您可以尝试以下方法(而不是使用 SqlCommand 对象):

string queryStr = "YOUR SQL QUERY HERE";
SqlCommand cmd = new SqlCommand(queryStr, new SqlConnection(connectionString));
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();

【讨论】:

  • 我在原始文件夹中有一个 MDF 文件,在 bin/Debug 文件夹中有相同的数据库。测试连接确实成功,然后我单击高级设置并复制底部的数据源链接,并将其粘贴到 ConnectToDatabse 字符串中。
  • @Rajan 我看到你的连接字符串中有很长的空格,所以也许你真的想确保你的代码中的连接字符串是正确的。
  • 只有在我提交问题时才会出现空格,因为您在提问时需要缩进。
  • @Rajan 无论如何,我在我的解决方案中添加了一些代码,您可以尝试使用这些代码进行连接并执行查询字符串,而不是使用 SqlCommand 的原始代码。
  • 查看上面初始 cmets 中提供的连接字符串链接..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
相关资源
最近更新 更多