String ConString = @"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BizContact.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(ConString);
try
{
cn.Open();
MessageBox.Show("connect");
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
SqlCommand cmd = new SqlCommand("insert tableNote values (@UserName,@Note)",cn);
cmd.Parameters.AddWithValue("@UserName", textBox1.Text);
cmd.Parameters.AddWithValue("@Note", textBox2.Text);
try
{
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("insert");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
我想向數據庫添加新行。上面的代碼是正確的,沒有錯誤,它顯示try語句,但不會將行插入到數據庫中。任何想法來解決它。從C#表格中插入行到數據庫
嘗試打印值處置的SqlConnection。它應該是1,因爲它給出了插入的行數。 – 2012-04-29 07:10:21
查看您的項目目錄,可能有多個'BizContact.mdf'副本檢查所有插入的記錄。 – gideon 2012-04-29 07:15:55
嘗試使用SQL Profiler並查看生成的查詢並嘗試在SSMS中運行它。 – praveen 2012-04-29 07:19:07