ADO.net连接数据库

参考了微软的资料http://chs.gotdotnet.com/quickstart/aspplus/
总结几点:

1.  为了使页能够访问执行SQL 数据必须将 System.Data 和System.Data.SqlClient 命名空间导入到页中
2.  创建与数据库的 SqlConnection,传递连接字符串,然后构造包含查询语句的 SqlDataAdapter 对象,调用命令的 Fill 方法把查询结果填充 DataSet 对象。
     SqlConnection myConnection = new SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes");
     SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
     DataSet ds = new DataSet();
     myCommand.Fill(ds, "Authors");
使用数据集的好处是它为您提供了断开连接的数据库视图。可以在应用程序中操作数据集,然后在以后协调更改和实际的数据库。对于长期运行的应用程序,这通常是最好的方法。

3.   请创建与数据库的 SqlConnection,传递连接字符串, 声明 SqlCommand ,SqlCommand 公开返回 SqlDataReader 的 ExecuteReader 方法。还请注意,当使用 SqlCommand 时,必须显式打开和关闭 SqlConnection。调用 ExecuteReader 后,SqlDataReader 可以绑定到 ASP.NET 服务器控件
SqlConnection myConnection = new SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes");
SqlCommand myCommand = new SqlCommand("select * from Authors", myConnection);
myConnection.Open();
...
SqlDataReader dr = myCommand.ExecuteReader();
...
myConnection.Close()

对于 Web 应用程序,通常对每个请求执行短操作(一般只是显示数据)。通常不需要在一系列请求间保持 DataSet 对象。对于这类情况,可以使用 SqlDataReader。SqlDataReader 对从 SQL 数据库检索的数据提供仅向前的只读指针.
4.当执行不要求返回数据的命令(如插入、更新和删除)时,也使用 SqlCommand。该命令通过调用 ExecuteNonQuery 方法发出,而该方法返回受影响的行数。注意当使用 SqlCommand 时,必须显式打开连接;SqlDataAdapter 自动为您处理如何打开连接
SqlConnection myConnection = new SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes");
SqlCommand myCommand = new SqlCommand("UPDATE Authors SET phone='(800) 555-5555' WHERE au_id = '123-45-6789'", myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
5.始终记住在页完成执行之前关闭与数据模型的连接。如果不关闭连接,则可能会在等待页实例被垃圾回收处理期间不经意地超过连接限制

原文地址:https://www.cnblogs.com/Love/p/1792239.html