新手写的三层架构里的数据库操作和登录检测,请大侠们提提意见。谢谢!

walkghost 2008-11-30 03:27:00
我是个新手,这个是我写的三层下的登录检测和一些对数据库操作的方法,用到一个检查用户名密码是否匹配的存储过程,和几个对数据库操作的类。希望大家提提意见。

1.检查用户名密码是否匹配的存储过程:


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

-- =============================================
-- Author: sixi
-- ALTER date: 2008,6,12
-- Description: Check Login.如果登陆成功,返回0;用户名错误,返回1;密码错误返回2
ALTER PROCEDURE [dbo].[CheckLog]
-- Add the parameters for the stored procedure here
@userID nvarchar(50),
@PWD nvarchar(50),
@rst int output
AS

if not exists
(
select * from userinfo where userID=@userID
)
BEGIN
select @rst=1
return
END
if not exists
(
select * from userinfo where userID=@userID and PWD=@PWD
)
BEGIN

SET NOCOUNT ON;
select @rst=2
return


END

BEGIN
select @rst=0
END








2.数据库操作类。


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 System.Data.SqlClient;

/**//// <summary>
/// This class include connection to the database and Execute SQl sentence.
/// </summary>
public class S_DataExecute
{
private string dbconn;
private SqlConnection conn ;
private SqlException sqlerror;
public S_DataExecute()
{//默认构造函数
dbconn = ConfigurationManager.ConnectionStrings["iqmsSup_BSConnectionString"].ConnectionString;
conn = new SqlConnection(dbconn);
sqlerror = null;

}
public SqlConnection getConn()
{//获取连接
return conn;
}
public void OpenConn()
{//打开连接
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
}
catch (SqlException e2)
{
sqlerror = e2;
}
}
public void CloseConn()
{//关闭连接
try
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}
catch (SqlException e2)
{
sqlerror = e2;
}
}
public SqlException GetSqlError()
{//获取错误
return sqlerror;
}

public SqlParameter MakeSqlParameter(string _ParameterName, int _length, SqlDbType _type,object _value,ParameterDirection direction)
{//构造sql语句参数
SqlParameter sp=new SqlParameter(_ParameterName, _type, _length);
if((direction!=ParameterDirection.Output)&&_value!=null)
sp.Value=_value;
sp.Direction = direction;
return sp;
}

public SqlDataReader ExecuteSQL(string sql)
{ //执行sql返回datareader,这个肯定有问题,因为在函数里不能关闭连接,到调用的时候,使用完了datareader之后才能关闭链接,很不方便,但我不知道怎么改
SqlDataReader rd;

SqlCommand cmd = new SqlCommand(sql,conn);
OpenConn();
if (sqlerror != null)
{
return null;
}

try
{
rd = cmd.ExecuteReader();
}
catch (SqlException e2)
{
rd = null;
sqlerror = e2;
}

return rd;

}

public int ExecuteSQLNoneQuery(string sql)
{//执行sqlNoneQuery
int i = 0;

SqlCommand cmd = new SqlCommand(sql, conn);
OpenConn();
if (sqlerror != null)
{
return i;
}

try
{
i = cmd.ExecuteNonQuery();
}
catch (SqlException e2)
{
sqlerror = e2;
}
finally
{
CloseConn();
}
return i;

}

public string ExecuteSQLScalar(string sql)
{//获取第一行第一列的值
string str="";

SqlCommand cmd = new SqlCommand(sql, conn);
OpenConn();
if (sqlerror != null)
{
return null;
}

try
{
str = cmd.ExecuteScalar().ToString();
}
catch (SqlException e2)
{
str = null;
sqlerror = e2;
}

return str;

}






public int CheckLogIn(string UserName, String PWD)
{
//如果登陆成功,返回0;用户名错误,返回1;密码错误返回2
int rst = -1;//默认为-1如果客户端检测到是-1则会查看sqlerror.message
SqlCommand cmd = new SqlCommand("checklog", this.getConn());
cmd.Parameters.Add(this.MakeSqlParameter("UserID",50,SqlDbType.NVarChar,UserName,ParameterDirection.Input));
cmd.Parameters.Add(this.MakeSqlParameter("PWD", 50, SqlDbType.NVarChar, PWD, ParameterDirection.Input));
SqlParameter sp = this.MakeSqlParameter("rst", 50, SqlDbType.Int, null, ParameterDirection.Output);
cmd.Parameters.Add(sp);
cmd.CommandType = CommandType.StoredProcedure;
try
{
this.OpenConn();
cmd.ExecuteNonQuery();
rst = int.Parse(sp.Value.ToString());
}
catch (SqlException e2)
{
this.sqlerror = e2;
}
finally
{
CloseConn();
}
return rst;
}
}

...全文
182 24 打赏 收藏 转发到动态 举报
写回复
用AI写文章
24 条回复
切换为时间正序
请发表友善的回复…
发表回复
wugaochao 2008-12-01
  • 打赏
  • 举报
回复
学习
zjybushiren88888 2008-12-01
  • 打赏
  • 举报
回复
比较规范了 顶楼主 细节方面差的不大
walkghost 2008-12-01
  • 打赏
  • 举报
回复
继续顶
walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 18 楼 yfqvip 的回复:]
遇到异常就抛出,这样一级级的往上抛就行,什么都不用管.在Global.asax.cs里有个protected void Application_Error(Object sender, EventArgs e)
在这里捕获所有的异常,统一处理,并跳到错误提示页面

C# codeprotected void Application_Start(Object sender, EventArgs e)
{
Application["tag"]=1;
}
protected void Application_Error(Object sender, EventArgs e)
{
try
{
if(Convert.ToInt32…
[/Quote]

晓得了,谢谢大侠,谢谢啦!
yilanwuyu123 2008-11-30
  • 打赏
  • 举报
回复
mark 写的不错
walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 16 楼 jiang_jiajia10 的回复:]
using是好东西所以建议LZ看sqlhelper
[/Quote]
再次感谢!继续等大家的意见。
满衣兄 2008-11-30
  • 打赏
  • 举报
回复
遇到异常就抛出,这样一级级的往上抛就行,什么都不用管.在Global.asax.cs里有个protected void Application_Error(Object sender, EventArgs e)
在这里捕获所有的异常,统一处理,并跳到错误提示页面
protected void Application_Start(Object sender, EventArgs e)
{
Application["tag"]=1;
}
protected void Application_Error(Object sender, EventArgs e)
{
try
{
if(Convert.ToInt32(Application["tag"])>2)
{
Application["tag"]=1;
return;
}
Application["tag"]=Convert.ToInt32(Application["tag"])+1;
Exception objErr = Server.GetLastError().GetBaseException();
Application["errorPage"] = Request.Url.ToString();
Application["errorMsg"] =objErr.Message;
Server.ClearError();
Response.Redirect("Error.aspx");
}
catch{}
}
Error.aspx.cs:
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
try
{
Application["tag"]=1;
lblError.Text=this.lblErrorPage.Text+Application["errorPage"].ToString()+"<br>"+this.lblErrorMsg.Text+Application["errorMsg"].ToString();
//写日志
WriterLog log = new WriterLog( Server.MapPath(@"./Log/Error.log"));
log.WriterError(Application["errorPage"].ToString(),Application["errorMsg"].ToString());
}
catch{}
}
}

walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 15 楼 tanjunqing 的回复:]
我们是这样写的,存储过程中
查询一下
然后在CS代码中看看DataTable中的Count>=0
>=0表示已经有用户了
[/Quote]
恩,我刚开始是用sql直接读到datareader的,谢谢关注。
jiang_jiajia10 2008-11-30
  • 打赏
  • 举报
回复
using是好东西所以建议LZ看sqlhelper
谈阿大 2008-11-30
  • 打赏
  • 举报
回复
我们是这样写的,存储过程中
查询一下
然后在CS代码中看看DataTable中的Count>=0
>=0表示已经有用户了
walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 yfqvip 的回复:]
没什么意见好提的,写的不错,唯一的缺点是要open和close,有的地方可以使用using语句块实现自动打开和释放连接.象下面这样:

C# code
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SqlC…
[/Quote]
恩,谢谢了。using是个好东西。自己关闭并销毁。
大侠,我对您的这个返回dateset的这个方法比较感兴趣:
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}

抛出异常之后,您专门写了个类来处理异常么?方法里是不是就一个return ErrorMessage;?在客户端如果发现dataset的数据为空的话,就去取异常?能麻烦您给我说一下您的这个异常处理的流程么?谢谢!
满衣兄 2008-11-30
  • 打赏
  • 举报
回复
没什么意见好提的,写的不错,唯一的缺点是要open和close,有的地方可以使用using语句块实现自动打开和释放连接.象下面这样:

/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, SqlConnection connection)
{
DataSet ds = new DataSet();
try
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}


walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 shadowjl 的回复:]
不错
[/Quote]
大侠,请问我的那个执行sql返回sqldataread的那个方法我觉得写得很不好,因为在方法里不能关闭连接,否则在客户端引用的时候,会提示reader没打开。有没有其他的解决办法?用out参数?
walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 shadowjl 的回复:]
不错
[/Quote]
大侠,请问我的那个执行sql返回sqldataread的那个方法我觉得写得很不好,因为在方法里不能关闭连接,否则在客户端引用的时候,会提示reader没打开。有没有其他的解决办法?用out参数?
shadowjl 2008-11-30
  • 打赏
  • 举报
回复
不错
walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 HDNGO 的回复:]
真是个耐心的人~
[/Quote]
呃。。。您指的是哪方面?我写的太繁琐了么?请提出意见,谢谢!
walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 yfqvip 的回复:]
LZ很强大
[/Quote]
高手,请提出意见,谢谢。
walkghost 2008-11-30
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 pt1314917 的回复:]
SQL code
ALTER PROCEDURE [dbo].[CheckLog]
-- Add the parameters for the stored procedure here
@userID nvarchar(50),
@PWD nvarchar(50),
@rst int output
AS

if not exists
(
select * from userinfo where userID=@userID
)
BEGIN
select @rst=1
return
END
if not exists
(
select * from userinfo where userID=@userID and PWD=@PWD
)

[/Quote]

谢谢,不需要else了,前面两条已经检查过用户名是否存在,用户名密码是否不相符,如果以上两条都没有return,那就肯定审核通过了,我这样写的话,不仅在登录的时候可以用,在注册的时候也可以用来检查用户名是否已经存在。
满衣兄 2008-11-30
  • 打赏
  • 举报
回复
LZ很强大
claymore1114 2008-11-30
  • 打赏
  • 举报
回复
up
加载更多回复(4)

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧