我有一個關於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