WebConfg
<appSettings>
<add key="SQLServerDAL" value="SQLServerDAL"/>
<!--<add key="OrdersDAL" value="OrdersDAL"/>-->
<add key="EnableSQLServer" value="true"/>
</appSettings>
<connectionStrings>
<add name="SQLConnString1" connectionString="Data Source=LJR\SQLEXPRESS;Initial Catalog=liyangdata;User ID=sa ; pwd=000000;" providerName="System.Data.SqlClient"/>
</connectionStrings>
BLL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IDAL;
using Model;
namespace BLL
{
/// <summary>
/// 用戶
/// </summary>
public class BPerson
{
IPerson person = DALFactory.DataAccess.CreatePerson();
/// <summary>
/// 取得所有用户
/// </summary>
/// <returns>成功则返回所有用户</returns>
public IList<MPerson> ListPerson()
{
return person.ListUser();
}
/// <summary>
/// 根据用户ID删除用户
/// </summary>
/// <param name="id">用户ID</param>
/// <returns>成功返回true 失败返回false</returns>
public bool DeletePersonByID(string id)
{
return person.DeleteUser(id);
}
/// <summary>
/// 根据用户ID返回用户信息
/// </summary>
/// <param name="id">用户ID</param>
/// <returns>成功则返回用户信息</returns>
public MPerson ListPersonByID(string id)
{
return person.ListUserByID(id);
}
/// <summary>
/// 根据用户名和密码返回用户
/// </summary>
/// <param name="name">用户名</param>
/// <param name="password">密码</param>
/// <returns>成功返回登录用户信息</returns>
public MPerson ListPersonByLogin(string name, string password)
{
return person.ListUserByLogin(name, password);
}
/// <summary>
/// 更新用户
/// </summary>
/// <param name="personInfo">用户信息</param>
/// <returns>成功则返回true 失败则返回false</returns>
public bool UpdatePerson(MPerson personInfo)
{
return person.UpdateUser(personInfo);
}
/// <summary>
/// 插入用户
/// </summary>
/// <param name="personInfo">用户信息</param>
/// <returns>成功返回true 失败返回false</returns>
public bool InsertPerson(MPerson personInfo)
{
return person.InsertUser(personInfo);
}
}
}
DALFactory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Reflection;
namespace DALFactory
{
public sealed class DataAccess
{
//获取要该问DLL
private static readonly string path = ConfigurationManager.AppSettings["SQLServerDAL"];
//是否开启
private static readonly bool enableSqlServer = bool.Parse(ConfigurationManager.AppSettings["EnableSQLServer"]);
private DataAccess()
{ }
/// <summary>
/// 创建静态方法选定DAL层的类
/// </summary>
/// <returns></returns>
public static IDAL.IPerson CreatePerson()
{
string className = null;
if (enableSqlServer)
{
className = path + ".DPerson";
}
else
{
//className = orderPath + ".Person";
}
return (IDAL.IPerson)Assembly.Load(path).CreateInstance(className);
}
}
}
common
sqlhelper
//===============================================================================
// This file is based on the Microsoft Data Access Application Block for .NET
// For more information please go to
// http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
//===============================================================================
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace Common
{
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance,
/// scalable best practices for common uses of SqlClient.
/// </summary>
public abstract class SqlHelper
{
//Database connection strings
// public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["WLKSsqlConnStr"].ConnectionString;
public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["SQLConnString1"].ConnectionString;
//WLKSsqlFengds
//public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString2"].ConnectionString;
//public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString;
//public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["SQLProfileConnString"].ConnectionString;
// Hashtable to store cached parameters
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="trans">an existing sql transaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the results</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
// we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// add parameter array to the cache
/// </summary>
/// <param name="cacheKey">Key to the parameter cache</param>
/// <param name="cmdParms">an array of SqlParamters to be cached</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
/// <summary>
/// Retrieve cached parameters
/// </summary>
/// <param name="cacheKey">key used to lookup parameters</param>
/// <returns>Cached SqlParamters array</returns>
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
if (cachedParms == null)
return null;
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
/// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name="cmd">SqlCommand object</param>
/// <param name="conn">SqlConnection object</param>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
/// <param name="cmdText">Command text, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
}
}
IDAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
namespace IDAL
{
public interface IPerson
{
/// <summary>
/// 人员信息增加
/// </summary>
/// <param name="personinfo">人员信息数据集</param>
/// <returns>true 成功,false 失败</returns>
bool InsertUser(MPerson prensoninfo);
/// <summary>
/// 人员信息修改
/// </summary>
/// <param name="personinfo">人员信息数据集</param>
/// <returns>true 成功,false 失败</returns>
bool UpdateUser(MPerson personinfo);
/// <summary>
/// 根据id删除人员信息
/// </summary>
/// <param name="ID">人员唯一id</param>
/// <returns>true 成功 false 失败</returns>
bool DeleteUser(string id);
/// <summary>
/// 根据人员id取得人员全部信息
/// </summary>
/// <param name="id">人员id</param>
/// <returns>无返回值为null</returns>
MPerson ListUserByID(string id);
/// <summary>
/// 根据人员姓名
/// </summary>
/// <param name="Name">用户名称</param>
/// <returns>无返回值为null</returns>
MPerson ListUserByName(string Name);
/// <summary>
/// 根据用户名和密码取得人员信息
/// </summary>
/// <param name="name">用户名</param>
/// <param name="password">密码</param>
/// <returns>无返回值时为null</returns>
MPerson ListUserByLogin(string name, string password);
/// <summary>
/// 取得全部人员信息
/// </summary>
/// <returns>全部人员信息</returns>
IList<MPerson> ListUser();
}
}
SQLServerDAL
using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using IDAL;
using Model;
using Common;
namespace SQLServerDAL
{
public class DPerson:IPerson
{
private const string SQLInsertUser = "INSERT INTO T_User(ID,Name,Password,Power,CreateTime) VALUES(@ID,@Name,@Password,@Power,@CreateTime)";
private const string Sql_UpdateUser = "Update T_User set Name=@Name,Password=@Password,Power=@Power,CreateTime=@CreateTime where ID=@ID";
private const string Sql_ListUserByID = "Select * from T_User where ID=@ID Order By CreateTime DESC";
private const string Sql_ListUserByName = "Select * from T_User where Name=@Name Order By CreateTime DESC";
private const string Sql_ListUserByLogin = "Select * from T_User where Name=@Name and Password=@Password Order By CreateTime DESC";
private const string Sql_ListUser = "Select * from T_User Order By CreateTime DESC";
#region IPerson 成员
/// <summary>
/// 用戶信息參數
/// </summary>
/// <param name="personInfo"></param>
/// <returns></returns>
private SqlParameter[] GetParamet(Model.MPerson personInfo)
{
SqlParameter [] paras = new SqlParameter[] {
new SqlParameter("@ID",personInfo.ID),
new SqlParameter("@Name",personInfo.Name),
new SqlParameter("@Password",personInfo.Password),
new SqlParameter("@Power",personInfo.Power),
new SqlParameter("@CreateTime",personInfo.CreateTime) };
return paras;
}
/// <summary>
/// 插入人員信息
/// </summary>
/// <param name="prensoninfo"></param>
/// <returns></returns>
bool IPerson.InsertUser(MPerson prensoninfo)
{
SqlParameter[] itemParas = GetParamet(prensoninfo);
int i = SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQLInsertUser, itemParas);
if (i > 0)
return true;
else
return false;
}
/// <summary>
/// 理新人員信息
/// </summary>
/// <param name="personinfo"></param>
/// <returns></returns>
bool IPerson.UpdateUser(MPerson personinfo)
{
int i = SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, Sql_UpdateUser, GetParamet(personinfo));
if (i > 0)
return true;
else
return false;
}
/// <summary>
/// 刪除人員信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
bool IPerson.DeleteUser(string id)
{
throw new NotImplementedException();
}
/// <summary>
/// 要据ID查詢用戶信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
MPerson IPerson.ListUserByID(string id)
{
Model.MPerson personInfo = new Model.MPerson();
SqlParameter itemPara = new SqlParameter("@ID", id);
using (SqlDataReader dataReader = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, Sql_ListUserByID, itemPara))
{
while (dataReader.Read())
{
personInfo.ID = id;
personInfo.Name = dataReader["Name"].ToString();
personInfo.Password = dataReader["Password"].ToString();
personInfo.Power = dataReader["Power"].ToString();
personInfo.CreateTime = (DateTime)dataReader["CreateTime"];
}
return personInfo;
}
}
/// <summary>
/// 要据姓名查詢
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
MPerson IPerson.ListUserByName(string Name)
{
Model.MPerson personInfo = new MPerson();
SqlParameter itemPara = new SqlParameter("@Name", Name);
using (SqlDataReader dataReader = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, Sql_ListUserByName, itemPara))
{
while (dataReader.Read())
{
personInfo.ID = dataReader["ID"].ToString();
personInfo.Name = Name;
personInfo.Power = dataReader["Power"].ToString();
personInfo.CreateTime = (DateTime)dataReader["CreateTime"];
}
return personInfo;
}
}
/// <summary>
/// 用戶登陸
/// </summary>
/// <param name="name"></param>
/// <param name="password"></param>
/// <returns></returns>
MPerson IPerson.ListUserByLogin(string name, string password)
{
Model.MPerson personInfo = new MPerson();
SqlParameter[] itemPara = new SqlParameter[] { new SqlParameter("@Name", name), new SqlParameter("@Password", password) };
using (SqlDataReader dataReader = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, Sql_ListUserByLogin, itemPara))
{
while (dataReader.Read())
{
personInfo.ID = dataReader["ID"].ToString();
personInfo.Name = name;
personInfo.Password = password;
personInfo.Power = dataReader["Power"].ToString();
personInfo.CreateTime = (DateTime)dataReader["CreateTime"];
}
return personInfo;
}
}
/// <summary>
/// 顯示所有用戶信息
/// </summary>
/// <returns></returns>
IList<Model.MPerson> IPerson.ListUser()
{
IList<Model.MPerson> personInfos = new List<Model.MPerson>();
using (SqlDataReader dataReader = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, Sql_ListUser, null))
{
while (dataReader.Read())
{
Model.MPerson personInfo = new Model.MPerson();
personInfo.ID = dataReader["ID"].ToString();
personInfo.Name = dataReader["Name"].ToString();
personInfo.Password = dataReader["Password"].ToString();
personInfo.Power = dataReader["Power"].ToString();
personInfo.CreateTime = (DateTime)dataReader["CreateTime"];
personInfos.Add(personInfo);
}
}
return personInfos;
}
#endregion
}
}
WEB
添加
//添加用户
Model.MPerson newPerson = new Model.MPerson();
newPerson.ID = Guid.NewGuid().ToString();
newPerson.Name = txbName.Text.ToString().Trim();
newPerson.Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txbPassword.Text.ToString().Trim(), "md5");
if (chkPower.Checked)
newPerson.Power = "管理员";
else
newPerson.Power = "普通用户";
newPerson.CreateTime = DateTime.Now;
if ((new BLL.BPerson()).InsertPerson(newPerson))
{
Common.JScript.Alert("插入用户成功!");
txbName.Text = "";
txbPassword.Text = "";
txbPassword1.Text = "";
}
else
{
Common.JScript.Alert("插入用户失败!");
}
刪除
if (e.CommandName == "del")
{
string id=new Guid(gvCommuntiy.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString()).ToString();
if ((new BLL.Person()).DeletePersonByID(id))
{
Common.JScript.Alert("删除用户成功!");
gvCommuntiy.DataBind();
}
else
{
Common.JScript.Alert("删除用户失败!");
}
}
密碼
string password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txbPassword.Text.ToString().Trim(), "md5");
if ((new BLL.Person()).UpdatePerson(UserInfo))
{
Common.JScript.Alert("更新成功!");
UserInfo.Password = password;
txbPassword.Text = "";
txbPassword1.Text = "";
}
else
{
Common.JScript.Alert("更新失败! ");
}