2010-09-28 61 views
2

我希望能夠使用C#教程C#連接到SQL Server

有人可以告訴我一個在SQL Server數據庫編輯表格非常簡單地連接到數據庫和編輯數據表中的教程

太感謝你了

+0

你需要通過GUI來編輯表格,或只是讓你的C#代碼更新呢? – 2010-09-28 17:38:00

+0

@steve我想在gui中編輯表格 – 2010-09-28 17:40:07

+0

爲什麼C#是一個需求呢?你不能只使用SQL Server Management Studio嗎? (可通過SQL Server Express免費獲得) – clifgriffin 2010-09-28 17:41:12

回答

4

假設你使用Visual Studio作爲你的IDE,你可以使用LINQ to SQL。這是一種非常簡單的與數據庫交互的方式,它應該很快就可以開始。

Using LINQ to SQL是一個非常簡單的通過啓動和運行。

2

在C#中這樣做的唯一原因是,如果您想以某種方式自動執行此操作,或者爲非技術用戶創建一個接口來與數據庫進行交互。您可以使用帶有SQL數據源的GridView控件來操作數據。

@kevin:如果他只是在學習,我認爲讓他使用SQLCommand對象(或SQLDataAdapter)可能更簡單。

10

第一步是創建一個連接。連接需要一個連接字符串。您可以使用SqlConnectionStringBuilder創建連接字符串。


SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder(); 
connBuilder.InitialCatalog = "DatabaseName"; 
connBuilder.DataSource = "ServerName"; 
connBuilder.IntegratedSecurity = true; 

然後使用連接字符串創建連接,像這樣:


SqlConnection conn = new SqlConnection(connBuilder.ToString()); 

//Use adapter to have all commands in one object and much more functionalities 
SqlDataAdapter adapter = new SqlDataAdapter("Select ID, Name, Address from myTable", conn); 
adapter.InsertCommand.CommandText = "Insert into myTable (ID, Name, Address) values(1,'TJ', 'Iran')"; 
adapter.DeleteCommand.CommandText = "Delete From myTable Where (ID = 1)"; 
adapter.UpdateCommand.CommandText = "Update myTable Set Name = 'Dr TJ' Where (ID = 1)"; 

//DataSets are like arrays of tables 
//fill your data in one of its tables 
DataSet ds = new DataSet(); 
adapter.Fill(ds, "myTable"); //executes Select command and fill the result into tbl variable 

//use binding source to bind your controls to the dataset 
BindingSource myTableBindingSource = new BindingSource(); 
myTableBindingSource.DataSource = ds; 

然後,就這麼簡單,你可以在綁定源使用AddNew()方法來添加新的記錄,然後用更新的方法保存

adapter.Update(ds, "myTable");

使用此命令來刪除一條記錄:

的適配器

,最好的辦法是增加一個DataSetProject->Add New Item菜單,然後按照嚮導...