我希望能够使用 C# 编辑 SQL Server 数据库中的表。
谁能给我一个关于连接到数据库和编辑表中数据的非常简单的教程。
非常感谢。
最佳答案
第一步是创建连接。连接需要一个连接字符串。您可以使用 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;
然后,很简单,您可以在绑定(bind)源中使用 AddNew()
方法来添加新记录,然后使用适配器的更新方法保存它:
adapter.Update(ds, "myTable");
使用此命令删除一条记录:
myTableBindingSource.RemoveCurrent();
adapter.Update(ds, "myTable");
最好的方法是从 Project->Add New Item
菜单添加一个 DataSet
并按照向导...
关于c# - 将c#连接到SQL服务器的教程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3815481/