我想了解如何在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查詢的人嗎?
當你打電話給你daCustomers.Fill(..)ADO.NET打開和關閉連接到數據庫 –