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

l--*_*''' 2 c# database sql-server

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

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

非常感谢

Dr *_* TJ 10

第一步是创建连接.连接需要一个连接字符串.你可以创建一个连接字符串SqlConnectionStringBuilder.


SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
connBuilder.InitialCatalog = "DatabaseName";
connBuilder.DataSource = "ServerName";
connBuilder.IntegratedSecurity = true;
Run Code Online (Sandbox Code Playgroud)

然后使用该连接字符串创建您的连接,如下所示:


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;
Run Code Online (Sandbox Code Playgroud)

然后,这么简单,您可以使用AddNew()绑定源中的方法添加新记录,然后使用适配器的更新方法保存它:

adapter.Update(ds, "myTable");
Run Code Online (Sandbox Code Playgroud)

使用此命令删除记录:

myTableBindingSource.RemoveCurrent();
adapter.Update(ds, "myTable");
Run Code Online (Sandbox Code Playgroud)

最好的办法是添加DataSetProject->Add New Item菜单,然后按照向导...