网上购物系统(Task002)——通用数据库访问函数
一、try…catch…finally结构
[csharp] using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using WestGarden.Model;
namespace WestGarden.Web
{
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IList<CategoryInfo> catogories = new List<CategoryInfo>();
string connectionString = ConfigurationManager.ConnectionStrings["NetShopConnString"].ConnectionString;
string cmdText = "SELECT * FROM Category";
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
try
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
CategoryInfo category = new CategoryInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetString(2));
catogories.Add(category);
}
rdr.Close();
}
finally
{
conn.Close();
}
ddlCategories.DataSource = catogories;
ddlCategories.DataTextField = "Name";
ddlCategories.DataValueField = "CategoryId";
ddlCategories.DataBind();
}
}
}
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using WestGarden.Model;
namespace WestGarden.Web
{
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IList<CategoryInfo> catogories = new List<CategoryInfo>();
string connectionString = ConfigurationManager.ConnectionStrings["NetShopConnString"].ConnectionString;
string cmdText = "SELECT * FROM Category";
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
try
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
CategoryInfo category = new CategoryInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetString(2));
catogories.Add(category);
}
rdr.Close();
}
finally
{
conn.Close();
}
ddlCategories.DataSource = catogories;
ddlCategories.DataTextField = "Name";
ddlCategories.DataValueField = "CategoryId";
ddlCategories.DataBind();
}
}
}
二、using()结构
[csharp] using System;
using System.Data;
using System.Data.SqlClient;
using System.Confi
补充:Web开发 , ASP.Net ,