ADO.NET 4 快速上手(4)——添、改、刪數據

四、    添、改、刪數據

1.    同步操作

// Assumes connection is a valid SqlConnection.
connection.Open();

string queryString = "INSERT INTO Customers (CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')";

SqlCommand command = new SqlCommand(queryString, connection);
Int32 recordsAffected = command.ExecuteNonQuery();

2.    非查詢操作異步操作

A.    異步阻塞

using (SqlConnection conn = new SqlConnection(
    "Data Source=localhost;Initial Catalog=SettingKnowledgeManagement;" +
    "Integrated Security=True;Asynchronous Processing=true"))
{
    string sql = "insert into tb_user values('tt', 'tt')";
    SqlCommand dataAction = new SqlCommand(sql, conn);
    conn.Open();

    IAsyncResult pending = dataAction.BeginExecuteNonQuery();
    while (pending.IsCompleted == false)
    {
        // do work
        Thread.Sleep(100);
    }

    dataAction.EndExecuteNonQuery(pending);
}

B.    異步回調

static void Main(string[] args)
{
    using (SqlConnection conn = new SqlConnection(
        "Data Source=localhost;Initial Catalog=SettingKnowledgeManagement;" +
        "Integrated Security=True;Asynchronous Processing=true"))
    {
        string sql = "insert into tb_user values('t2', 't2')";
        SqlCommand dataAction = new SqlCommand(sql, conn);
        conn.Open();

        AsyncCallback callback = new AsyncCallback(Finished);
        dataAction.BeginExecuteNonQuery(callback, dataAction);
    }

    Console.ReadKey();
}

private static void Finished(IAsyncResult r)
{
    SqlCommand dataAction = (SqlCommand)r.AsyncState;
    dataAction.EndExecuteNonQuery(r);
}
發佈了32 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章