前台页面*.aspx 有个用户控件:
开发商</td>
1 <td>
2 <uc3:ProductCompany ID="ProductCompany1" runat="server" />
3 </td>
2 <uc3:ProductCompany ID="ProductCompany1" runat="server" />
3 </td>
2
用户控件代码如下
1 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ProductCompany.ascx.cs" Inherits="Controls_ProductCompany" %>
2 <asp:DropDownList ID="ddlCompanys" runat="server">
3
4 </asp:DropDownList>
2 <asp:DropDownList ID="ddlCompanys" runat="server">
3
4 </asp:DropDownList>
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.HtmlControls;
10
11 public partial class Controls_ProductCompany : System.Web.UI.UserControl
12 {
13 protected void Page_PreRender(object sender, EventArgs e)
14 {
15 if (!IsPostBack)
16 {
17 DBind();
18 }
19 }
20
21 private void DBind()
22 {
23 ddlCompanys.DataSource = new CMS.BLL.Company().GetAllCompanys();
24 ddlCompanys.DataTextField = "Name";
25 ddlCompanys.DataValueField = "ID";
26 ddlCompanys.DataBind();
27
28 ddlCompanys.Items.Insert(0, new ListItem("无所属厂商", "0"));
29
30 if (ddlCompanys.SelectedValue != "")
31 ddlCompanys.Items.FindByValue(ddlCompanys.SelectedValue).Selected = false;
32 if (ViewState["Company"] != null)
33 {
34 ListItem selectedItem = ddlCompanys.Items.FindByValue(ViewState["Company"].ToString());
35 if (selectedItem != null)
36 selectedItem.Selected = true;
37 }
38 }
39
40 public int Company
41 {
42 get { return int.Parse(ddlCompanys.SelectedValue); }
43 set
44 { ViewState["Company"] = value.ToString(); }
45 }
2 using System.Data;
3 using System.Configuration;
4 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.HtmlControls;
10
11 public partial class Controls_ProductCompany : System.Web.UI.UserControl
12 {
13 protected void Page_PreRender(object sender, EventArgs e)
14 {
15 if (!IsPostBack)
16 {
17 DBind();
18 }
19 }
20
21 private void DBind()
22 {
23 ddlCompanys.DataSource = new CMS.BLL.Company().GetAllCompanys();
24 ddlCompanys.DataTextField = "Name";
25 ddlCompanys.DataValueField = "ID";
26 ddlCompanys.DataBind();
27
28 ddlCompanys.Items.Insert(0, new ListItem("无所属厂商", "0"));
29
30 if (ddlCompanys.SelectedValue != "")
31 ddlCompanys.Items.FindByValue(ddlCompanys.SelectedValue).Selected = false;
32 if (ViewState["Company"] != null)
33 {
34 ListItem selectedItem = ddlCompanys.Items.FindByValue(ViewState["Company"].ToString());
35 if (selectedItem != null)
36 selectedItem.Selected = true;
37 }
38 }
39
40 public int Company
41 {
42 get { return int.Parse(ddlCompanys.SelectedValue); }
43 set
44 { ViewState["Company"] = value.ToString(); }
45 }
3
1 Page_Load
2 ProductCompany1.Company = product.Developer;
3
4 btnSave_Click
5 product.Developer = ProductCompany1.Company;
6
2 ProductCompany1.Company = product.Developer;
3
4 btnSave_Click
5 product.Developer = ProductCompany1.Company;
6
以下为其他层的写法
4 BLL层的Company的GetAllCompanys()方法
1 public class Company
2 {
3 private static ICompany dal = DALFactory.DataAccess.CreateCompany();
4
5 public IList<CompanyInfo> GetAllCompanys()
6 {
7 return dal.GetCompanys();
8 }
9
2 {
3 private static ICompany dal = DALFactory.DataAccess.CreateCompany();
4
5 public IList<CompanyInfo> GetAllCompanys()
6 {
7 return dal.GetCompanys();
8 }
9
5 interface层的 ICompany
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using CMS.Model;
5
6 namespace CCNEC.CMS.IDAL
7 {
8 public interface ICompany
9 {
10 IList<CompanyInfo> GetCompanys();
11
12 CompanyInfo GetCompanyByID(int companyid);
13
14 void Add(CompanyInfo company);
15
16 void Modify(CompanyInfo company);
17 }
18 }
19
2 using System.Collections.Generic;
3 using System.Text;
4 using CMS.Model;
5
6 namespace CCNEC.CMS.IDAL
7 {
8 public interface ICompany
9 {
10 IList<CompanyInfo> GetCompanys();
11
12 CompanyInfo GetCompanyByID(int companyid);
13
14 void Add(CompanyInfo company);
15
16 void Modify(CompanyInfo company);
17 }
18 }
19
6 Model层 CompanyInfo
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace CMS.Model
6 {
7 public class CompanyInfo:Base
8 {
9 public CompanyInfo()
10 : base()
11 {
12 m_Address = String.Empty;
13 m_WebSite = String.Empty;
14 m_Summary = String.Empty;
15 }
16
17 public CompanyInfo(System.Data.IDataRecord dr)
18 {
19 base.ID = Convert.ToInt32(dr["companyID"]);
20 m_CompanyName = Convert.ToString(dr["companyName"]);
21 m_CompanyEnName = Convert.ToString(dr["companyEnName"]);
22 m_Country = Convert.ToString(dr["country"]);
23 m_Logo = Convert.ToString(dr["logo"]);
24 m_Address = Convert.ToString(dr["address"]);
25 m_WebSite = Convert.ToString(dr["Website"]);
26 m_Summary = Convert.ToString(dr["summary"]);
27 }
28
29 private String m_CompanyName;
30 private String m_CompanyEnName;
31 private String m_Country;
32 private String m_Logo;
33 private String m_Address;
34 private String m_WebSite;
35 private String m_Summary;
36
37 public String Name
38 {
39 get { return m_CompanyName; }
40 set { m_CompanyName = value; }
41 }
42 public String EnglishName
43 {
44 get { return m_CompanyEnName; }
45 set { m_CompanyEnName = value; }
46 }
47 public String Country
48 {
49 get { return m_Country; }
50 set { m_Country = value; }
51 }
52 public String Logo
53 {
54 get { return m_Logo; }
55 set { m_Logo = value; }
56 }
57 public String Address
58 {
59 get { return m_Address; }
60 set { m_Address = value; }
61 }
62 public String WebSite
63 {
64 get { return m_WebSite; }
65 set { m_WebSite = value; }
66 }
67 public String Summary
68 {
69 get { return m_Summary; }
70 set { m_Summary = value; }
71 }
72 }
73 }
74
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace CMS.Model
6 {
7 public class CompanyInfo:Base
8 {
9 public CompanyInfo()
10 : base()
11 {
12 m_Address = String.Empty;
13 m_WebSite = String.Empty;
14 m_Summary = String.Empty;
15 }
16
17 public CompanyInfo(System.Data.IDataRecord dr)
18 {
19 base.ID = Convert.ToInt32(dr["companyID"]);
20 m_CompanyName = Convert.ToString(dr["companyName"]);
21 m_CompanyEnName = Convert.ToString(dr["companyEnName"]);
22 m_Country = Convert.ToString(dr["country"]);
23 m_Logo = Convert.ToString(dr["logo"]);
24 m_Address = Convert.ToString(dr["address"]);
25 m_WebSite = Convert.ToString(dr["Website"]);
26 m_Summary = Convert.ToString(dr["summary"]);
27 }
28
29 private String m_CompanyName;
30 private String m_CompanyEnName;
31 private String m_Country;
32 private String m_Logo;
33 private String m_Address;
34 private String m_WebSite;
35 private String m_Summary;
36
37 public String Name
38 {
39 get { return m_CompanyName; }
40 set { m_CompanyName = value; }
41 }
42 public String EnglishName
43 {
44 get { return m_CompanyEnName; }
45 set { m_CompanyEnName = value; }
46 }
47 public String Country
48 {
49 get { return m_Country; }
50 set { m_Country = value; }
51 }
52 public String Logo
53 {
54 get { return m_Logo; }
55 set { m_Logo = value; }
56 }
57 public String Address
58 {
59 get { return m_Address; }
60 set { m_Address = value; }
61 }
62 public String WebSite
63 {
64 get { return m_WebSite; }
65 set { m_WebSite = value; }
66 }
67 public String Summary
68 {
69 get { return m_Summary; }
70 set { m_Summary = value; }
71 }
72 }
73 }
74
7 SQLServerDAL层的Company
1 using System;
2 using System.Collections.Generic;
3 using System.Data;
4 using System.Data.SqlClient;
5 using System.Text;
6 using CMS.IDAL;
7 using CMS.Model;
8 using DBUtility;
9
10 namespace CMS.SQLServerDAL
11 {
12 public class Company:ICompany
13 {
14 private static string SQL_SELECT_ALL_COMPANYS = "SELECT * FROM [Companys]";
15 private static string SQL_SELECT_COMPANY_BY_ID = "SELECT * FROM [Companys] WHERE Companyid=@companyid";
16 private static string SQL_INSERT_COMPANY = "INSERT INTO Companys ([CompanyName],[CompanyEnName],[Country],[Logo],[Address],[Website],[Summary])VALUES(@CompanyName,@CompanyEnName,@Country,@Logo,@Address,@Website,@Summary)";
17 private static string SQL_UPDATE_COMPANY = "UPDATE Companys SET [CompanyName]=@CompanyName,[CompanyEnName]=@CompanyEnName,[Country]=@Country,[Logo]=@Logo,[Address]=@Address,[Website]=@Website,[Summary]=@Summary WHERE [CompanyID]=@CompanyID";
18
19 #region ICompany Members
20
21 public IList<CompanyInfo> GetCompanys()
22 {
23 IList<CompanyInfo> items = new List<CompanyInfo>();
24 using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringPub, CommandType.Text, SQL_SELECT_ALL_COMPANYS, (SqlParameter[])null))
25 {
26 while (dr.Read())
27 items.Add(new CompanyInfo(dr));
28 }
29 return items;
30 }
31
32 public CompanyInfo GetCompanyByID(int companyid)
33 {
34 SqlParameter[] arParms = { new SqlParameter("@companyid",SqlDbType.Int) };
35 arParms[0].Value = companyid;
36
37 using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringPub, CommandType.Text, SQL_SELECT_COMPANY_BY_ID, arParms))
38 {
39 if (dr.Read())
40 return new CompanyInfo(dr);
41 }
42 return null;
43 }
44
45 public void Add(CompanyInfo company)
46 {
47 SqlParameter[] arParms = {
48 new SqlParameter("@CompanyName" ,SqlDbType.VarChar ,50),
49 new SqlParameter("@CompanyEnName" ,SqlDbType.VarChar ,50),
50 new SqlParameter("@Country" ,SqlDbType.VarChar ,50),
51 new SqlParameter("@Logo" ,SqlDbType.VarChar ,256),
52 new SqlParameter("@Address" ,SqlDbType.VarChar ,256),
53 new SqlParameter("@Website" ,SqlDbType.VarChar ,256),
54 new SqlParameter("@Summary" ,SqlDbType.Text)
55 };
56 int i = 0;
57 arParms[i++].Value = company.Name;
58 arParms[i++].Value = company.EnglishName;
59 arParms[i++].Value = company.Country;
60 arParms[i++].Value = company.Logo;
61 arParms[i++].Value = company.Address;
62 arParms[i++].Value = company.WebSite;
63 arParms[i++].Value = company.Summary;
64
65 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringPub))
66 {
67 SqlHelper.ExecuteNonQuery(conn, CommandType.Text, SQL_INSERT_COMPANY, arParms);
68 }
69 }
70
71 public void Modify(CompanyInfo company)
72 {
73 SqlParameter[] arParms = {
74 new SqlParameter("@CompanyID" ,SqlDbType.Int ,4),
75 new SqlParameter("@CompanyName" ,SqlDbType.VarChar ,50),
76 new SqlParameter("@CompanyEnName" ,SqlDbType.VarChar ,50),
77 new SqlParameter("@Country" ,SqlDbType.VarChar ,50),
78 new SqlParameter("@Logo" ,SqlDbType.VarChar ,256),
79 new SqlParameter("@Address" ,SqlDbType.VarChar ,256),
80 new SqlParameter("@Website" ,SqlDbType.VarChar ,256),
81 new SqlParameter("@Summary" ,SqlDbType.Text ,0)
82 };
83 int i = 0;
84 arParms[i++].Value = company.ID;
85 arParms[i++].Value = company.Name;
86 arParms[i++].Value = company.EnglishName;
87 arParms[i++].Value = company.Country;
88 arParms[i++].Value = company.Logo;
89 arParms[i++].Value = company.Address;
90 arParms[i++].Value = company.WebSite;
91 arParms[i++].Value = company.Summary;
92
93 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringPub))
94 {
95 SqlHelper.ExecuteNonQuery(conn, CommandType.Text, SQL_UPDATE_COMPANY, arParms);
96 }
97 }
98
99 #endregion
100 }
101 }
102
2 using System.Collections.Generic;
3 using System.Data;
4 using System.Data.SqlClient;
5 using System.Text;
6 using CMS.IDAL;
7 using CMS.Model;
8 using DBUtility;
9
10 namespace CMS.SQLServerDAL
11 {
12 public class Company:ICompany
13 {
14 private static string SQL_SELECT_ALL_COMPANYS = "SELECT * FROM [Companys]";
15 private static string SQL_SELECT_COMPANY_BY_ID = "SELECT * FROM [Companys] WHERE Companyid=@companyid";
16 private static string SQL_INSERT_COMPANY = "INSERT INTO Companys ([CompanyName],[CompanyEnName],[Country],[Logo],[Address],[Website],[Summary])VALUES(@CompanyName,@CompanyEnName,@Country,@Logo,@Address,@Website,@Summary)";
17 private static string SQL_UPDATE_COMPANY = "UPDATE Companys SET [CompanyName]=@CompanyName,[CompanyEnName]=@CompanyEnName,[Country]=@Country,[Logo]=@Logo,[Address]=@Address,[Website]=@Website,[Summary]=@Summary WHERE [CompanyID]=@CompanyID";
18
19 #region ICompany Members
20
21 public IList<CompanyInfo> GetCompanys()
22 {
23 IList<CompanyInfo> items = new List<CompanyInfo>();
24 using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringPub, CommandType.Text, SQL_SELECT_ALL_COMPANYS, (SqlParameter[])null))
25 {
26 while (dr.Read())
27 items.Add(new CompanyInfo(dr));
28 }
29 return items;
30 }
31
32 public CompanyInfo GetCompanyByID(int companyid)
33 {
34 SqlParameter[] arParms = { new SqlParameter("@companyid",SqlDbType.Int) };
35 arParms[0].Value = companyid;
36
37 using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringPub, CommandType.Text, SQL_SELECT_COMPANY_BY_ID, arParms))
38 {
39 if (dr.Read())
40 return new CompanyInfo(dr);
41 }
42 return null;
43 }
44
45 public void Add(CompanyInfo company)
46 {
47 SqlParameter[] arParms = {
48 new SqlParameter("@CompanyName" ,SqlDbType.VarChar ,50),
49 new SqlParameter("@CompanyEnName" ,SqlDbType.VarChar ,50),
50 new SqlParameter("@Country" ,SqlDbType.VarChar ,50),
51 new SqlParameter("@Logo" ,SqlDbType.VarChar ,256),
52 new SqlParameter("@Address" ,SqlDbType.VarChar ,256),
53 new SqlParameter("@Website" ,SqlDbType.VarChar ,256),
54 new SqlParameter("@Summary" ,SqlDbType.Text)
55 };
56 int i = 0;
57 arParms[i++].Value = company.Name;
58 arParms[i++].Value = company.EnglishName;
59 arParms[i++].Value = company.Country;
60 arParms[i++].Value = company.Logo;
61 arParms[i++].Value = company.Address;
62 arParms[i++].Value = company.WebSite;
63 arParms[i++].Value = company.Summary;
64
65 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringPub))
66 {
67 SqlHelper.ExecuteNonQuery(conn, CommandType.Text, SQL_INSERT_COMPANY, arParms);
68 }
69 }
70
71 public void Modify(CompanyInfo company)
72 {
73 SqlParameter[] arParms = {
74 new SqlParameter("@CompanyID" ,SqlDbType.Int ,4),
75 new SqlParameter("@CompanyName" ,SqlDbType.VarChar ,50),
76 new SqlParameter("@CompanyEnName" ,SqlDbType.VarChar ,50),
77 new SqlParameter("@Country" ,SqlDbType.VarChar ,50),
78 new SqlParameter("@Logo" ,SqlDbType.VarChar ,256),
79 new SqlParameter("@Address" ,SqlDbType.VarChar ,256),
80 new SqlParameter("@Website" ,SqlDbType.VarChar ,256),
81 new SqlParameter("@Summary" ,SqlDbType.Text ,0)
82 };
83 int i = 0;
84 arParms[i++].Value = company.ID;
85 arParms[i++].Value = company.Name;
86 arParms[i++].Value = company.EnglishName;
87 arParms[i++].Value = company.Country;
88 arParms[i++].Value = company.Logo;
89 arParms[i++].Value = company.Address;
90 arParms[i++].Value = company.WebSite;
91 arParms[i++].Value = company.Summary;
92
93 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringPub))
94 {
95 SqlHelper.ExecuteNonQuery(conn, CommandType.Text, SQL_UPDATE_COMPANY, arParms);
96 }
97 }
98
99 #endregion
100 }
101 }
102
8 DBUtility层的SQLHelper
1 //===============================================================================
2 // This file is based on the Microsoft Data Access Application Block for .NET
3 // For more information please go to
4 // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
5 //===============================================================================
6
7 using System;
8 using System.Configuration;
9 using System.Data;
10 using System.Data.SqlClient;
11 using System.Collections;
12
13 namespace DBUtility {
14
15 /// <summary>
16 /// The SqlHelper class is intended to encapsulate high performance,
17 /// scalable best practices for common uses of SqlClient.
18 /// </summary>
19 public abstract class SqlHelper {
20
21 //Database connection strings
22 public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["SQLConnString1"].ConnectionString;
23 public static readonly string ConnectionStringBBS = ConfigurationManager.ConnectionStrings["SQLConnString2"].ConnectionString;
24 public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString;
25 public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["SQLProfileConnString"].ConnectionString;
26
27 // Hashtable to store cached parameters
28 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
29
30 /// <summary>
31 /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
32 /// using the provided parameters.
33 /// </summary>
34 /// <remarks>
35 /// e.g.:
36 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
37 /// </remarks>
38 /// <param name="connectionString">a valid connection string for a SqlConnection</param>
39 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
40 /// <param name="commandText">the stored procedure name or T-SQL command</param>
41 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
42 /// <returns>an int representing the number of rows affected by the command</returns>
43 public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
44
45 SqlCommand cmd = new SqlCommand();
46
47 using (SqlConnection conn = new SqlConnection(connectionString)) {
48 PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
49 int val = cmd.ExecuteNonQuery();
50 cmd.Parameters.Clear();
51 return val;
52 }
53 }
54
55 /// <summary>
56 /// Execute a SqlCommand (that returns no resultset) against an existing database connection
57 /// using the provided parameters.
58 /// </summary>
59 /// <remarks>
60 /// e.g.:
61 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
62 /// </remarks>
63 /// <param name="conn">an existing database connection</param>
64 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
65 /// <param name="commandText">the stored procedure name or T-SQL command</param>
66 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
67 /// <returns>an int representing the number of rows affected by the command</returns>
68 public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
69
70 SqlCommand cmd = new SqlCommand();
71
72 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
73 int val = cmd.ExecuteNonQuery();
74 cmd.Parameters.Clear();
75 return val;
76 }
77
78 /// <summary>
79 /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction
80 /// using the provided parameters.
81 /// </summary>
82 /// <remarks>
83 /// e.g.:
84 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
85 /// </remarks>
86 /// <param name="trans">an existing sql transaction</param>
87 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
88 /// <param name="commandText">the stored procedure name or T-SQL command</param>
89 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
90 /// <returns>an int representing the number of rows affected by the command</returns>
91 public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
92 SqlCommand cmd = new SqlCommand();
93 PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
94 int val = cmd.ExecuteNonQuery();
95 cmd.Parameters.Clear();
96 return val;
97 }
98
99 /// <summary>
100 /// Execute a SqlCommand that returns a resultset against the database specified in the connection string
101 /// using the provided parameters.
102 /// </summary>
103 /// <remarks>
104 /// e.g.:
105 /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
106 /// </remarks>
107 /// <param name="connectionString">a valid connection string for a SqlConnection</param>
108 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
109 /// <param name="commandText">the stored procedure name or T-SQL command</param>
110 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
111 /// <returns>A SqlDataReader containing the results</returns>
112 public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
113 SqlCommand cmd = new SqlCommand();
114 SqlConnection conn = new SqlConnection(connectionString);
115
116 // we use a try/catch here because if the method throws an exception we want to
117 // close the connection throw code, because no datareader will exist, hence the
118 // commandBehaviour.CloseConnection will not work
119 try {
120 PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
121 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
122 cmd.Parameters.Clear();
123 return rdr;
124 }
125 catch {
126 conn.Close();
127 throw;
128 }
129 }
130
131 /// <summary>
132 /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
133 /// using the provided parameters.
134 /// </summary>
135 /// <remarks>
136 /// e.g.:
137 /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
138 /// </remarks>
139 /// <param name="connectionString">a valid connection string for a SqlConnection</param>
140 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
141 /// <param name="commandText">the stored procedure name or T-SQL command</param>
142 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
143 /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
144 public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
145 SqlCommand cmd = new SqlCommand();
146
147 using (SqlConnection connection = new SqlConnection(connectionString)) {
148 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
149 object val = cmd.ExecuteScalar();
150 cmd.Parameters.Clear();
151 return val;
152 }
153 }
154
155 /// <summary>
156 /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
157 /// using the provided parameters.
158 /// </summary>
159 /// <remarks>
160 /// e.g.:
161 /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
162 /// </remarks>
163 /// <param name="conn">an existing database connection</param>
164 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
165 /// <param name="commandText">the stored procedure name or T-SQL command</param>
166 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
167 /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
168 public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
169
170 SqlCommand cmd = new SqlCommand();
171
172 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
173 object val = cmd.ExecuteScalar();
174 cmd.Parameters.Clear();
175 return val;
176 }
177
178 /// <summary>
179 /// add parameter array to the cache
180 /// </summary>
181 /// <param name="cacheKey">Key to the parameter cache</param>
182 /// <param name="cmdParms">an array of SqlParamters to be cached</param>
183 public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) {
184 parmCache[cacheKey] = commandParameters;
185 }
186
187 /// <summary>
188 /// Retrieve cached parameters
189 /// </summary>
190 /// <param name="cacheKey">key used to lookup parameters</param>
191 /// <returns>Cached SqlParamters array</returns>
192 public static SqlParameter[] GetCachedParameters(string cacheKey) {
193 SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
194
195 if (cachedParms == null)
196 return null;
197
198 SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
199
200 for (int i = 0, j = cachedParms.Length; i < j; i++)
201 clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
202
203 return clonedParms;
204 }
205
206 /// <summary>
207 /// Prepare a command for execution
208 /// </summary>
209 /// <param name="cmd">SqlCommand object</param>
210 /// <param name="conn">SqlConnection object</param>
211 /// <param name="trans">SqlTransaction object</param>
212 /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
213 /// <param name="cmdText">Command text, e.g. Select * from Products</param>
214 /// <param name="cmdParms">SqlParameters to use in the command</param>
215 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) {
216
217 if (conn.State != ConnectionState.Open)
218 conn.Open();
219
220 cmd.Connection = conn;
221 cmd.CommandText = cmdText;
222
223 if (trans != null)
224 cmd.Transaction = trans;
225
226 cmd.CommandType = cmdType;
227
228 if (cmdParms != null) {
229 foreach (SqlParameter parm in cmdParms)
230 cmd.Parameters.Add(parm);
231 }
232 }
233 }
234 }
2 // This file is based on the Microsoft Data Access Application Block for .NET
3 // For more information please go to
4 // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
5 //===============================================================================
6
7 using System;
8 using System.Configuration;
9 using System.Data;
10 using System.Data.SqlClient;
11 using System.Collections;
12
13 namespace DBUtility {
14
15 /// <summary>
16 /// The SqlHelper class is intended to encapsulate high performance,
17 /// scalable best practices for common uses of SqlClient.
18 /// </summary>
19 public abstract class SqlHelper {
20
21 //Database connection strings
22 public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["SQLConnString1"].ConnectionString;
23 public static readonly string ConnectionStringBBS = ConfigurationManager.ConnectionStrings["SQLConnString2"].ConnectionString;
24 public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString;
25 public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["SQLProfileConnString"].ConnectionString;
26
27 // Hashtable to store cached parameters
28 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
29
30 /// <summary>
31 /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
32 /// using the provided parameters.
33 /// </summary>
34 /// <remarks>
35 /// e.g.:
36 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
37 /// </remarks>
38 /// <param name="connectionString">a valid connection string for a SqlConnection</param>
39 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
40 /// <param name="commandText">the stored procedure name or T-SQL command</param>
41 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
42 /// <returns>an int representing the number of rows affected by the command</returns>
43 public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
44
45 SqlCommand cmd = new SqlCommand();
46
47 using (SqlConnection conn = new SqlConnection(connectionString)) {
48 PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
49 int val = cmd.ExecuteNonQuery();
50 cmd.Parameters.Clear();
51 return val;
52 }
53 }
54
55 /// <summary>
56 /// Execute a SqlCommand (that returns no resultset) against an existing database connection
57 /// using the provided parameters.
58 /// </summary>
59 /// <remarks>
60 /// e.g.:
61 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
62 /// </remarks>
63 /// <param name="conn">an existing database connection</param>
64 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
65 /// <param name="commandText">the stored procedure name or T-SQL command</param>
66 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
67 /// <returns>an int representing the number of rows affected by the command</returns>
68 public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
69
70 SqlCommand cmd = new SqlCommand();
71
72 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
73 int val = cmd.ExecuteNonQuery();
74 cmd.Parameters.Clear();
75 return val;
76 }
77
78 /// <summary>
79 /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction
80 /// using the provided parameters.
81 /// </summary>
82 /// <remarks>
83 /// e.g.:
84 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
85 /// </remarks>
86 /// <param name="trans">an existing sql transaction</param>
87 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
88 /// <param name="commandText">the stored procedure name or T-SQL command</param>
89 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
90 /// <returns>an int representing the number of rows affected by the command</returns>
91 public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
92 SqlCommand cmd = new SqlCommand();
93 PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
94 int val = cmd.ExecuteNonQuery();
95 cmd.Parameters.Clear();
96 return val;
97 }
98
99 /// <summary>
100 /// Execute a SqlCommand that returns a resultset against the database specified in the connection string
101 /// using the provided parameters.
102 /// </summary>
103 /// <remarks>
104 /// e.g.:
105 /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
106 /// </remarks>
107 /// <param name="connectionString">a valid connection string for a SqlConnection</param>
108 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
109 /// <param name="commandText">the stored procedure name or T-SQL command</param>
110 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
111 /// <returns>A SqlDataReader containing the results</returns>
112 public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
113 SqlCommand cmd = new SqlCommand();
114 SqlConnection conn = new SqlConnection(connectionString);
115
116 // we use a try/catch here because if the method throws an exception we want to
117 // close the connection throw code, because no datareader will exist, hence the
118 // commandBehaviour.CloseConnection will not work
119 try {
120 PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
121 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
122 cmd.Parameters.Clear();
123 return rdr;
124 }
125 catch {
126 conn.Close();
127 throw;
128 }
129 }
130
131 /// <summary>
132 /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
133 /// using the provided parameters.
134 /// </summary>
135 /// <remarks>
136 /// e.g.:
137 /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
138 /// </remarks>
139 /// <param name="connectionString">a valid connection string for a SqlConnection</param>
140 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
141 /// <param name="commandText">the stored procedure name or T-SQL command</param>
142 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
143 /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
144 public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
145 SqlCommand cmd = new SqlCommand();
146
147 using (SqlConnection connection = new SqlConnection(connectionString)) {
148 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
149 object val = cmd.ExecuteScalar();
150 cmd.Parameters.Clear();
151 return val;
152 }
153 }
154
155 /// <summary>
156 /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
157 /// using the provided parameters.
158 /// </summary>
159 /// <remarks>
160 /// e.g.:
161 /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
162 /// </remarks>
163 /// <param name="conn">an existing database connection</param>
164 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
165 /// <param name="commandText">the stored procedure name or T-SQL command</param>
166 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
167 /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
168 public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
169
170 SqlCommand cmd = new SqlCommand();
171
172 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
173 object val = cmd.ExecuteScalar();
174 cmd.Parameters.Clear();
175 return val;
176 }
177
178 /// <summary>
179 /// add parameter array to the cache
180 /// </summary>
181 /// <param name="cacheKey">Key to the parameter cache</param>
182 /// <param name="cmdParms">an array of SqlParamters to be cached</param>
183 public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) {
184 parmCache[cacheKey] = commandParameters;
185 }
186
187 /// <summary>
188 /// Retrieve cached parameters
189 /// </summary>
190 /// <param name="cacheKey">key used to lookup parameters</param>
191 /// <returns>Cached SqlParamters array</returns>
192 public static SqlParameter[] GetCachedParameters(string cacheKey) {
193 SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
194
195 if (cachedParms == null)
196 return null;
197
198 SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
199
200 for (int i = 0, j = cachedParms.Length; i < j; i++)
201 clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
202
203 return clonedParms;
204 }
205
206 /// <summary>
207 /// Prepare a command for execution
208 /// </summary>
209 /// <param name="cmd">SqlCommand object</param>
210 /// <param name="conn">SqlConnection object</param>
211 /// <param name="trans">SqlTransaction object</param>
212 /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
213 /// <param name="cmdText">Command text, e.g. Select * from Products</param>
214 /// <param name="cmdParms">SqlParameters to use in the command</param>
215 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) {
216
217 if (conn.State != ConnectionState.Open)
218 conn.Open();
219
220 cmd.Connection = conn;
221 cmd.CommandText = cmdText;
222
223 if (trans != null)
224 cmd.Transaction = trans;
225
226 cmd.CommandType = cmdType;
227
228 if (cmdParms != null) {
229 foreach (SqlParameter parm in cmdParms)
230 cmd.Parameters.Add(parm);
231 }
232 }
233 }
234 }
以上就是这样的思路方法,也请高手指教得失,献丑了,也祝愿新手们共同进步,都在学习中。以上代码仅供参考。
欢迎转载但是请珍惜我的劳动,写明出处地址http://www.cnblogs.com/jazzking/archive/2007/02/25/655706.html