2012-04-29 33 views
0
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#表格中插入行到數據庫

+0

嘗試打印值處置的SqlConnection。它應該是1,因爲它給出了插入的行數。 – 2012-04-29 07:10:21

+0

查看您的項目目錄,可能有多個'BizContact.mdf'副本檢查所有插入的記錄。 – gideon 2012-04-29 07:15:55

+0

嘗試使用SQL Profiler並查看生成的查詢並嘗試在SSMS中運行它。 – praveen 2012-04-29 07:19:07

回答

3

您的插入語句錯誤(缺少into)。請執行:

insert into tableNote select @UserName,@Note 

insert into tableNote (column_name1, column_name2) values (@UserName,@Note) 
0

打開SQL事件探查器,看着它執行該命令,然後嘗試重新那個命令到SQL Management Studio中。更可能的是,它會告訴你,查詢是如此微不足道,以至於它無法成功地做任何事情。

4

嘗試完全T-SQL語句

"INSERT INTO table_name (userColumn, noteColumn) VALUES (@UserName, @Note)" 

也可以通過使用狀態

res`的`
using(SqlConnection cn = new SqlConnection(ConString)) 
{ 
    //.... 
} 
相關問題