2013-02-27 58 views
1

我需要將文本框值添加到SQL Server數據庫表。下面是我的代碼:使用c將文本框值插入到sql服務器#

private void button1_Click(object sender, EventArgs e) 
{ 
    string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True"; 
    SqlConnection con = new SqlConnection(str); 
    string qry = "insert into SubjectMaster (SubjectName) values (@TxtSubjectName)"; 
    con.Open(); 
    SqlCommand cmd = new SqlCommand(qry, con); 
    cmd.CommandType = CommandType.Text; 
    cmd.Parameters.AddWithValue("@TxtSubjectName", TxtSubjectName.Text); 
    cmd.ExecuteNonQuery(); 
    MessageBox.Show("Added Successfully!!"); 
    con.Close(); 
} 

不過,數據應在表中未添加......請幫我... 感謝烏拉圭回合的幫助...

+0

你有文件'timetablesystem.mdf'您的項目文件和上市之間其屬性「複製到輸出目錄」設置爲「始終複製」? – Steve 2013-02-27 11:48:59

+0

在將代碼放入代碼之前,您是否嘗試先調試您的查詢? – user15 2013-02-27 11:49:26

+0

可能的重複:http://stackoverflow.com/questions/9363061/how-to-insert-record-into-a-sql-server-express-database-table – 2013-02-27 11:50:00

回答

0

首先嚐試調試你的查詢,如果它的工作原理我認爲你的數據庫連接不起作用。

string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True"; 

是否應該是這個'。'數據源後Data Source=.\\SQLEXPRESS

-1

試試這個

 SqlConnection con = new SqlConnection(@"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;"); 
     string query = " insert into name(name)values('" + TextboxTest.Text + "')"; 
     con.Open(); 
     SqlCommand cmd = new SqlCommand(query, con); 
     cmd.ExecuteNonQuery(); 
     con.Close(); 
0

試試這個,告訴我什麼是郵件信息內容

private void button1_Click(object sender, EventArgs e) 
{ 
    string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;"; 
    using(SqlConnection con = new SqlConnection(str)){ 
          try{ 
           con.Open(); 
           string qry = "insert into SubjectMaster (SubjectName) values (@TxtSubjectName)"; 
           SqlCommand cmd = new SqlCommand(qry, con); 
           cmd.CommandType = CommandType.Text; 
           cmd.Parameters.AddWithValue("@TxtSubjectName", TxtSubjectName.Text); 
           cmd.ExecuteNonQuery(); 
           MessageBox.Show("Added Successfully!!"); 
           } 
          catch{ 
           MessageBox.Show("connection is failed!!"); 
           } 
                 } 
}