我有一个关于C#的问题。我用ASP.net编写了一个函数,当用户点击按钮时,它应该调用这个函数并将sql插入本地数据库。但是,我不知道为什么它不起作用。谁能帮我?C#如何连接本地数据库(访问)
我的本地数据库是Access,它存储在'App_Data'文件夹下。
protected void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(connectionString);
// I think the problem is here, but I don't know how to do
SqlCommand myCommand = new SqlCommand("INSERT INTO [car] ([carName], [carType]) VALUES (@carName, @carType)", myConnection);
SqlParameter carName= myCommand.Parameters.Add("@carName", SqlDbType.Text);
SqlParameter carType= myCommand.Parameters.Add("@carType", SqlDbType.Text);
carName.Value = carNametb.Text;
carType.Value = carTypetb.Text;
myConnection.Open();
myCommand.ExecuteNonQuery();
// need to close() the connection where?
}
你应该在SqlCommand对象周围使用using语句,这会帮助你,因为它以一种处理良好的方式关闭连接,即使有异常。 Hanselman可以解释这比我更好http://www.hanselman.com/blog/WhyTheUsingStatementIsBetterThanASharpStickInTheEyeAndASqlConnectionRefactoringExample.aspx – 2012-02-13 04:48:03
@李贝克,我尝试键入它,但错误发生在myConnection.Open()语句 – 2012-02-13 05:10:58
这听起来像一个连接字符串问题。 using语句只是让你的代码更健壮。 – 2012-02-13 05:16:19