2010-09-28 62 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菜单,然后按照向导...