[英]Connect to an MDF Database
In Visual Studio Form, Im creating ac# application.在 Visual Studio 表单中,我正在创建 ac# 应用程序。 Im an trying to add data entered into a register form and save it into the MDF Database file i cretased with tables.
我试图将输入的数据添加到注册表中,并将其保存到我用表格创建的 MDF 数据库文件中。 But i cant connect to the database, Any Help?
但是我无法连接到数据库,有什么帮助吗?
My Register Button Code when its clicked单击时我的注册按钮代码
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);
}
}
There are a few things to help you get connected.有一些事情可以帮助您建立联系。 I just helped several students had their connections done this week.
我刚刚帮助几个学生在本周完成了他们的联系。
Please double check your connection string is correct (pointing to the right location - path of your .MDF file)请仔细检查您的连接字符串是否正确(指向正确的位置 - .MDF 文件的路径)
Test Connection
button.Test Connection
按钮。 Click it and ensure connection is working before you try to execute query from the codes.Select * FROM tblName
query statement to test first instead of using an insert statement which is more prone to typo error.Select * FROM tblName
查询语句进行测试,而不是使用更容易出现拼写错误的插入语句。 You can try the following (instead of using a SqlCommand
object):您可以尝试以下操作(而不是使用
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.