连接数据库需要配置Web.config的Sql server,WebDAL节点是需要生成抽象工厂的实例,本登陆用到了3层结构+反射抽象工厂,才疏学浅,请大家多多指教。
BLL类:
using System;
using System.Collections.Generic;
using System.Text;
using Logindemo.IDAL;
using Logindemo.Model;
using Logindemo.DALFactory;
namespace Logindemo.BLL
{
public class Login
{
//利用反射生成实例
private static readonly ILogin denglu = Logindemo.DALFactory.DataAccess.CreateLogin();
//登陆
public int denglula(Logininfo log)
{
return denglu.Logining(log);
}
}
}
DALFactory类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Reflection;
namespace Logindemo.DALFactory
{
//此类用于实现抽象工厂模式去创建从配置文件指定的数据访问层的实例
public sealed class DataAccess
{
private static readonly string path = System.Configuration.ConfigurationManager.AppSettings["WebDAL"];
//实现 CreateLogin 方法,用于创建Login类实例
public static Logindemo.IDAL.ILogin CreateLogin()
{
string classname = path + ".Login";
return (Logindemo.IDAL.ILogin)Assembly.Load(path).CreateInstance(classname);
}
}
}
IDAL类:
using System;
using System.Collections.Generic;
using System.Text;
using Logindemo.Model;
namespace Logindemo.IDAL
{
/// <summary>
/// 登陆用户接口
/// </summary>
public interface ILogin
{
/// <summary>
/// 用户登陆
/// </summary>
/// <param name="Log">登陆的Logininfo类型</param>
/// <returns></returns>
int Logining(Logininfo Log);
}
}
IDAL类:
using System;
using System.Collections.Generic;
using System.Text;
namespace Logindemo.Model
{
/// <summary>
/// 用户实体
/// </summary>
public class Logininfo
{
private string _loginUser;
private string _loginPass;
/// <summary>
/// 获取或设置用户名
/// </summary>
public string LoginUser
{
set { _loginUser = value; }
get { return _loginUser; }
}
/// <summary>
/// 获取或设置用户密码
/// </summary>
public string LoginPass
{
set { _loginPass = value; }
get { return _loginPass; }
}
}
}
SQLserver类库包括两个类文件:
Login.cs:
using System;
using System.Collections.Generic;
using System.Text;
using Logindemo.IDAL;
using Logindemo.Model;
using System.Data.SqlClient;
using System.Data;
namespace Logindemo.SQLserver
{
/// <summary>
/// 登陆用户
/// </summary>
public class Login:ILogin
{
private const string SQL_SELECT_USER = "SELECT LoginUser,LoginPassWord from LoginUser WHERE LoginUser=@LoginUser and LoginPassWord=@LoginPassWord";
private const string LOGIN_USER="@LoginUser";
private const string LOGIN_PASS = "@LoginPassWord";
/// <summary>
/// 用户登陆
/// </summary>
/// <param name="Log">登陆的Logininfo类型</param>
/// <returns></returns>
public int Logining(Logininfo Log) //重写ILogin的Logining接口
{
SqlParameter[] loginParameter = GetLoginParameters();
int loginState;
loginParameter[0].Value = Log.LoginUser;
loginParameter[1].Value = Log.LoginPass;
using (SqlDataReader sdr = SqlHelper.ExecuteReader(SqlHelper.Con, CommandType.Text, SQL_SELECT_USER, loginParameter))
{
if (sdr.Read())
{
loginState = 1;
}
else
{
loginState = 0;
}
sdr.Dispose();
}
return loginState;
}
/// <summary>
/// 获取SQL参数缓存
/// </summary>
/// <returns>参数数组</returns>
private static SqlParameter[] GetLoginParameters()
{
SqlParameter[] parms = SqlHelper.GetCachedParameters(SQL_SELECT_USER);
if (parms == null)
{
parms = new SqlParameter[]{new SqlParameter(LOGIN_USER,SqlDbType.VarChar,10),
new SqlParameter(LOGIN_PASS,SqlDbType.VarChar,10)
};
SqlHelper.CacheParameters(SQL_SELECT_USER, parms);
}
return parms;
}
}
}
SQLHelper:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace Logindemo.SQLserver
{
/// <summary>
/// SqlHelper类是专门提供给广大用户用于高性能、可升级和最佳练习的sql数据操作
/// </summary>
public abstract class SqlHelper
{
//数据库连接字符串
public static readonly string Con = System.Configuration.ConfigurationManager.AppSettings["SQLServer"];
// 用于缓存参数的HASH表
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// 给定连接的数据库用假设参数执行一个sql命令(不返回数据集)
/// </summary>
/// <param name="connectionString">一个有效的连接字符串</param>
/// <param name="commandType">命令类型(存储过程, 文本, 等等)</param>
/// <param name="commandText">存储过程名称或者sql命令语句</param>
/// <param name="commandParameters">执行命令所用参数的集合</param>
/// <returns>执行命令所影响的行数</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>
/// 用现有的数据库连接执行一个sql命令(不返回数据集)
/// </summary>
/// <param name="conn">一个现有的数据库连接</param>
/// <param name="commandType">命令类型(存储过程, 文本, 等等)</param>
/// <param name="commandText">存储过程名称或者sql命令语句</param>
/// <param name="commandParameters">执行命令所用参数的集合</param>
/// <returns>执行命令所影响的行数</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>
///使用现有的SQL事务执行一个sql命令(不返回数据集)
/// </summary>
/// <remarks>
///举例:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="trans">一个现有的事务</param>
/// <param name="commandType">命令类型(存储过程, 文本, 等等)</param>
/// <param name="commandText">存储过程名称或者sql命令语句</param>
/// <param name="commandParameters">执行命令所用参数的集合</param>
/// <returns>执行命令所影响的行数</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>
/// 用执行的数据库连接执行一个返回数据集的sql命令
/// </summary>
/// <remarks>
/// 举例:
/// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的连接字符串</param>
/// <param name="commandType">命令类型(存储过程, 文本, 等等)</param>
/// <param name="commandText">存储过程名称或者sql命令语句</param>
/// <param name="commandParameters">执行命令所用参数的集合</param>
/// <returns>包含结果的读取器</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
//创建一个SqlCommand对象
SqlCommand cmd = new SqlCommand();
//创建一个SqlConnection对象
SqlConnection conn = new SqlConnection(connectionString);
//在这里我们用一个try/catch结构执行sql文本命令/存储过程,因为如果这个方法产生一个异常我们要关闭连接,因为没有读取器存在,
//因此commandBehaviour.CloseConnection 就不会执行
try
{
//调用 PrepareCommand 方法,对 SqlCommand 对象设置参数
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
//调用 SqlCommand 的 ExecuteReader 方法
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
//清除参数
cmd.Parameters.Clear();
return reader;
}
catch
{
//关闭连接,抛出异常
conn.Close();
throw;
}
}
/// <summary>
/// 用指定的数据库连接字符串执行一个命令并返回一个数据集的第一列
/// </summary>
/// <remarks>
///例如:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
///<param name="connectionString">一个有效的连接字符串</param>
/// <param name="commandType">命令类型(存储过程, 文本, 等等)</param>
/// <param name="commandText">存储过程名称或者sql命令语句</param>
/// <param name="commandParameters">执行命令所用参数的集合</param>
/// <returns>用 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>
/// 用指定的数据库连接执行一个命令并返回一个数据集的第一列
/// </summary>
/// <remarks>
/// 例如:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">一个存在的数据库连接</param>
/// <param name="commandType">命令类型(存储过程, 文本, 等等)</param>
/// <param name="commandText">存储过程名称或者sql命令语句</param>
/// <param name="commandParameters">执行命令所用参数的集合</param>
/// <returns>用 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>
/// 将参数集合添加到缓存
/// </summary>
/// <param name="cacheKey">添加到缓存的变量</param>
/// <param name="cmdParms">一个将要添加到缓存的sql参数集合</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
/// <summary>
/// 找回缓存参数集合
/// </summary>
/// <param name="cacheKey">用于找回参数的关键字</param>
/// <returns>缓存的参数集合</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>
/// 准备执行一个命令
/// </summary>
/// <param name="cmd">sql命令</param>
/// <param name="conn">Sql连接</param>
/// <param name="trans">Sql事务</param>
/// <param name="cmdType">命令类型例如 存储过程或者文本</param>
/// <param name="cmdText">命令文本,例如:Select * from Products</param>
/// <param name="cmdParms">执行命令的参数</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);
}
}
}
}
在web.config文件中配置这个 <appSettings>
<add key="WebDAL" value="Logindemo.SQLserver"/><!--实例化类型-->
<add key="SQLServer" value="Server=./SQL2005;DataBase=Logindemo;user id=sa;password=123;"/>
</appSettings>。
页面文件的代码如下:
<form id="form1" runat="server">
<table>
<tr>
<td>
帐号:
</td>
<td align="left">
<asp:TextBox ID="txtUser" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>密码:</td>
<td>
<asp:TextBox ID="txtPass" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2" style="height: 40px" align="center">
<asp:Button ID="btnLogin" runat="server" Text="登 陆" CssClass="btnLogin" OnClick="btnLogin_Click" Width="86px" /> </td>
</tr>
</table>
<asp:Label ID="lbMsg" runat="server"></asp:Label>
</form>
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Logindemo.Model;
using Logindemo.BLL;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
Logindemo.Model.Logininfo logif = new Logininfo();
logif.LoginUser = txtUser.Text.Trim();
logif.LoginPass = txtPass.Text.Trim();
Logindemo.BLL.Login lg = new Logindemo.BLL.Login();
int i = lg.denglula(logif);
if (i == 1)
{
lbMsg.Text = "<font color=green>恭喜!登陆成功</font>";
}
else
{
lbMsg.Text = "<font color=red>对不起,登陆失败</font>";
}
}
}