C#-如可insert a values to a ms sql server?

2008-11-14 7:54 am
String go = "Data Source=xxxxx;Database=xxxxx;"
SqlConnection con = new SqlConnection(go);
con.Open();

連左去個sql server, 可以select something from table, 但如果我有個string values,e.g. string mes1 ="boy" , string mes2 ="girl" ,應如何insert 到個sql server?? ( 我希望用string variable 代替 insert into table values('boy' , 'girl') )

回答 (2)

2008-11-14 10:26 am
✔ 最佳答案
con.Open();
SqlCommand cmd = con.CreateCommand();
string sql = "INSERT INTO Table1 VALUES ('" + mes1 + "','" + mes2 + "')";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();


A better method:
con.Open();
SqlCommand cmd = con.CreateCommand();
string sql = "INSERT INTO Table1 VALUES (@field1, @field2)";
cmd.CommandText = sql;
cmd.Parameters.Add(new SqlParameter("@field1", SqlType.VarChar, 100)).Value = mes1;
cmd.Parameters.Add(new SqlParameter("@field2", SqlType.VarChar, 100)).Value = mes2;
cmd.ExecuteNonQuery();
2008-11-14 5:58 pm
簡單情況, 當然可以用command做.
不過, 於開發角度看, 個人較喜歡使用typed dataset, 配合adapter, 這會使編寫時出錯的機會會較少, 因為用typed ds, 是不會因打錯字而使程式出錯, 用command就會. 但用command一樣有好處, 就是開發速度快點.


收錄日期: 2021-04-12 10:57:04
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20081113000051KK01747

檢視 Wayback Machine 備份