2012-10-09 63 views
1

我想了解如何在C#中使用數據庫,當我必須使用DataSet,SqlDataAdapter和SqlCommandBuilder時,我得到了教程中的一部分。這是我寫的代碼在本教程中的例子:在C中使用數據庫混淆#

public void InitData() { 
     //instantiate the connection 
     conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"D:\\Projects IDE\\Visual Studio\\Exercitii\\Console.app\\WindowsFormsApplication1\\WindowsFormsApplication1\\PlanetWrox.mdf\";Integrated Security=True;User Instance=True"); 

     //1.instantiate a new DataSet 
     dsCustomers = new DataSet(); 

     //2.init SqlDataAdapter with select command and connection 
     daCustomers = new SqlDataAdapter("SELECT Id ,Name, SortOrder FROM Genre", conn); 

     // 3. fill in insert, update, and delete commands 
     SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers); 

     // 4. fill the dataset 
     daCustomers.Fill(dsCustomers, tableName); 
    } 

    public void btnUpdateClicked(object sender, EventArgs e) { 
     // write changes back to DataBase 
     daCustomers.Update(dsCustomers, tableName); 

    } 

有一對夫婦的事情,我不明白,在這裏:

我注意到的第一件事是,我沒有打開和關閉database.From什麼關於數據庫的知識有限我知道,爲了訪問數據,你必須打開數據庫的連接,完成後你必須關閉數據庫。這必須發生在場景後面的某個地方。那是不是?如果那是巫婆的方法呢?

第二個問題是關於SqlDataAdapter和SqlCommandBuilder.I不明白SqlCommandBuilder在這裏做什麼。不是SqlDataAdapter是執行sql查詢的人嗎?

+1

當你打電話給你daCustomers.Fill(..)ADO.NET打開和關閉連接到數據庫 –

回答

2

我注意到的第一件事就是填寫你的表是我沒有打開和關閉 數據庫。

SqldataAdapter.Fill將爲您打開/關閉連接。

如果在調用Fill之前IDbConnection已關閉,則會打開到 檢索數據,然後關閉。如果在調用填充 之前連接已打開,則它保持打開狀態。

SqlCommandBuilder根據您提供的select語句的元數據生成INSERT,UPDATE或DELETE語句。通過這種方式,您可以撥打daCustomers.Update,並且對數據庫中的DataSet所做的所有更改都會自動更新。

1

dsCustomers.Fill爲您打開和關閉連接。 SqlCommandBuilder根據您的select語句創建插入,更新和刪除。

1

ADO.NET爲您處理這個任務,當你與數據

0
//instantiate the connection 
    using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"D:\\Projects IDE\\Visual Studio\\Exercitii\\Console.app\\WindowsFormsApplication1\\WindowsFormsApplication1\\PlanetWrox.mdf\";Integrated Security=True;User Instance=True")) 
    { 
    //1.instantiate a new DataSet 
    dsCustomers = new DataSet(); 

    //2.init SqlDataAdapter with select command and connection 
    daCustomers = new SqlDataAdapter("SELECT Id ,Name, SortOrder FROM Genre", conn); 

    // 3. fill in insert, update, and delete commands 
    SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers); 

    // 4. fill the dataset 
    daCustomers.Fill(dsCustomers, tableName); 
    } 

這會自動關閉連接和Dispose,而不必擔心。

0

Fill將使所有的resources locked that are involved in the process。 同樣根據sql設置,它也可能會阻塞其他資源。

如果您使用此代碼進行一些實時工作..請僅在需要時選擇此代碼。

0

爲了您的第一件事:

我們使用conn.open();打開連接和conn.close();關閉連接。

在你的程序中,你並沒有連接到像sqlserver這樣的數據庫。您已經提供了顯示文件的物理路徑。

請參閱下面的第二件事:

SqlCommandBuilder Class