簡體   English   中英

連接到 MDF 數據庫

[英]Connect to an MDF Database

在 Visual Studio 表單中,我正在創建 ac# 應用程序。 我試圖將輸入的數據添加到注冊表中,並將其保存到我用表格創建的 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);
    }
}  

有一些事情可以幫助您建立聯系。 我剛剛幫助幾個學生在本周完成了他們的聯系。

請仔細檢查您的連接字符串是否正確(指向正確的位置 - .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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM