1、需要使用时 new sqlconnection & open,使用完后 close & dispose,这种是最简单的,但是,性能不多说(有可能一个页面需要做100次重复操作)。
如果有人使用 executereader 方法的话(未读完数据不能关闭 connection),项目庞大以后,这时如果有一处忘了 close & dispose,可能会影响系统的正常运行。
因为每次都是 new sqlconnection,所以不能扩展事务。
2、添加页面对象 sqlconnection,一直 open,页面访问结束时 close & dispose,性能较好,但是,灵活性差,程序结构也变得难看。
简单应用
<%@ page language="c#" %>
<%@ import namespace="system.data.sqlclient" %>
<%@ import namespace="system.web.configuration" %>
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
void page_load()
{
string connectionstring = webconfigurationmanager.connectionstrings["products"].connectionstring;
sqlconnection con = new sqlconnection(connectionstring);
sqlcommand cmd = new sqlcommand("waitfor delay '0:0:03';select title,director from products", con);
con.statisticsenabled = true;
using (con)
{
con.open();
sqldatareader reader = cmd.executereader();
}
grdstats.datasource = con.retrievestatistics();
grdstats.databind();
}
show all statistics
file: web.config
connectionstring="data source=.sqlexpress;
attachdbfilename=|datadirectory|mydatabase.mdf;integrated security=true;user instance=true" />
一个复杂一点的数据库连接
file: app_codeproduct.cs
using system;
using system.data;
using system.data.sqlclient;
using system.web.configuration;
using system.collections;
using system.collections.generic;public class product
{
private static readonly string _connectionstring;private string _title;
private string _director;public string title
{
get { return _title; }
set { _title = value; }
}public string director
{
get { return _director; }
set { _director = value; }
}public list
getall(out long executiontime)
{
listresults = new list ();
sqlconnection con = new sqlconnection(_connectionstring);
sqlcommand cmd = new sqlcommand("waitfor delay '0:0:03';select title, director from products", con);
con.statisticsenabled = true;
using (con)
{
con.open();
sqldatareader reader = cmd.executereader();
while (reader.read())
{
product newproduct = new product();
newproduct.title = (string)reader["title"];
newproduct.director = (string)reader["director"];
results.add(newproduct);
}
}
idictionary stats = con.retrievestatistics();
executiontime = (long)stats["executiontime"];
return results;
}static product()
{
_connectionstring = webconfigurationmanager.connectionstrings["products"].connectionstring;
}
}file: web.config
connectionstring="data source=.sqlexpress;
attachdbfilename=|datadirectory|mydatabase.mdf;integrated security=true;user instance=true" />
file: default.aspx
<%@ page language="c#" %>
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
show product
1、建立一个数据库连接对象 conn
2、指定欲连接的数据库参数:服务器为本地服务器,数据库名'news’,用户id为'sa',密码为'123'
3、建立一个command对象 cmd
4、将cmd的connection变量赋值为第1步建立的对象conn
5、for循环遍历gridview1控件里的每一行
6、获得gridview1第i行里的‘checkbox1’属性
7、判断checkbox是否选中
8、为cmd指定执行内容,更新数据库‘主题表’里‘主帖编号’="+gridview1 .datakeys[i].value的那一行里‘审核’字段内容为‘已审核’
9、连接数据库
10、执行第8步指定的内容
11、关闭数据库连接