关于将c#连接到sql server的教程

我希望能够使用c#编辑SQL Server数据库中的表

有人可以给我一个关于连接数据库和编辑表格数据的简单教程

非常感谢

假设您使用Visual Studio作为IDE,您可以使用LINQ to SQL。 这是一种与数据库交互的非常简单的方法,它应该很快就能开始。

使用LINQ to SQL是一个非常简单的步骤,让它启动并运行。

第一步是创建连接。 连接需要连接字符串。 您可以使用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"); 

使用此命令删除记录:

 myTableBindingSource.RemoveCurrent(); adapter.Update(ds, "myTable"); 

最好的方法是从Project->Add New Item菜单添加一个DataSet ,然后按照向导…

阅读有关创建数据应用程序的MSDN教程 。 您可以澄清您的问题,或找到您需要的答案。

有关于在应用程序中编辑数据的信息,但您必须先连接并将其加载到您的应用程序中。

在C#中执行此操作的唯一原因是,如果您想以某种方式自动化它,或者为非技术用户创建一个与数据库交互的接口。 您可以将GridView控件与SQL数据源一起使用来操作数据。

@kevin:如果他刚刚学习,我认为让他使用SQLCommand对象(或SQLDataAdapter)可能更简单。