[英]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 文件的路徑)
Test Connection
按鈕。 單擊它並確保連接正常,然后再嘗試從代碼執行查詢。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.