c# - 将c#连接到SQL服务器的教程

标签 c# sql-server database

我希望能够使用 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/

相关文章:

c# - 将 List<BaseClass> 复制到 List<DerivedClass>

c# - 自动更新 Visual Studio 扩展

sql - 创建计算列并舍入

database - 如何在没有秒的情况下将 TIMESTAMP 导入 POSTGRES?来自大型 CSV

mysql - 如何安全地加密数据库中的信用卡信息

php - 查询通过 phpmyadmin 执行,但不通过 php 脚本执行

c# - 如何触发 WebHandler 请求的 session 开始 (Global.asax) 事件?

c# - 将多头列表转换为字符串数组

sql - 如何在此查询中获取每一天的 MAX(Hour) 和 The MIN(Hour)?

sql - 有什么办法可以在sql server management studio中查看上次运行的sql查询