2012-11-13 78 views
1

我退出繁忙時,將舊的經典asp網站轉換爲.NET網站。另外我現在正在使用SQL Server。如何使用C#向SQL Server插入/更新行

現在我有一些舊的代碼

strsql = "select * FROM tabel WHERE ID = " & strID & " AND userid = " & struserid 
rs1.open strsql, strCon, 2, 3 

if rs1.eof THEN 
    rs1.addnew 
end if 

if straantal <> 0 THEN 
    rs1("userid") = struserid 
    rs1("verlangid") = strID 
    rs1("aantal") = straantal 
end if 

rs1.update 
rs1.close 

我想在SQL Server中使用。更新方式。我怎樣才能做到這一點?

  • 我如何檢查DataReader的是EOF/EOL
  • 我怎樣才能插入一行ID是EOF/EOL
  • 我怎樣才能更新行或刪除行與一個功能?
+3

閱讀關於實體框架 – mcalex

+0

閱讀關於SqlDataAdapter或ADO.Net的一般信息 – codingbiz

回答

0

這取決於你使用的方法......你打算使用實體框架和LINQ?你打算使用直接的SQL連接嗎?我會強烈建議下去了EF路線,但一個簡單直接的SQL代碼片段看起來是這樣的:

using (var connection = new SqlConnection("Your connection string here")) 
{ 
    connection.Open(); 
    using (var command = new SqlCommand("SELECT * FROM xyz ETC", connection)) 
    {     
     // Process results 
     using (SqlDataReader reader = command.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       int userId = (int)reader["UserID"]; 
       string somethingElse = (string)reader["AnotherField"]; 
       // Etc, etc... 
      } 
     } 
    } 

    // To execute a query (INSERT, UPDATE, DELETE etc) 
    using (var commandExec = new SqlCommand("DELETE * FROM xyz ETC", connection)) 
    { 
     commandExec.ExecuteNonQuery(); 
    } 
} 

您將使用注意包裹在的各種元素,那是因爲你需要釋放內存/連接當你完成。這應該很快回答你的問題,但正如其他人所建議的(包括我),我會調查實體框架,因爲它更強大,但附帶了學習曲線!

2

如果你想使用原始的SQL命令,你可以嘗試這樣的事情

using (SqlConnection cnn = new SqlConnection(_connectionString)) 
using (SqlCommand cmd = new SqlCommand()) 
{ 
    cnn.Open(); 
    cmd.Connection = cnn; 

    // Example of reading with SqlDataReader 
    cmd.CommandText = "select sql query here"; 

    using (SqlDataReader reader = cmd.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      myList.Add((int)reader[0]); 
     } 
    } 

    // Example of updating row 
    cmd.CommandText = "update sql query here"; 

    cmd.ExecuteNonQuery(); 
} 
0

您可以使用SQL存儲過程進行更新。並通過C#調用此存儲過程。

創建過程[DBO]。[xyz_Update] ( @ PARA1 @ PARA2 ) AS BEGIN 更新TABLENAME 集Fieldname1 = @ PARA1, 集Feildname2 = @ PARA2

相關問題