前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="UserLogin.Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
用户名<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
密码<asp:TextBox ID="TextBox2"
runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnLogin" runat="server" Text="登录" οnclick="btnLogin_Click" />
</div>
</form>
</body>
</html>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace UserLogin
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//表示层的作用就是现实数据给用户看,或者收集用户输入的数据,并且将数据传递到BLL层
UserLogin.Model.T_User muser = new Model.T_User();
muser.UserName = TextBox1.Text;
muser.Password = TextBox2.Text;
UserLogin.BLL.T_User btuser = new BLL.T_User();
if (btuser.ValidatorUser(muser) == true)
{
Response.Write("成功");
}
else
{
Response.Write("失败");
}
#region 原始方式验证登录
/*using (SqlConnection conn=new SqlConnection("strcon"))
{
using (SqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = "select * from T_User where username=@usernmae and password=@password";
//参数替换
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Write("登录成功");
}
else
{
Response.Write("登录失败");
}
}
}*/
#endregion
}
}
}
BLL类:
/** 版本信息模板在安装目录下,可自行修改。
* T_User.cs
*
* 功 能: N/A
* 类 名: T_User
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2013/4/2 15:19:11 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Collections.Generic;
using UserLogin.Model;
namespace UserLogin.BLL
{
/// <summary>
/// T_User
/// </summary>
public partial class T_User
{
private readonly UserLogin.DAL.T_User dal=new UserLogin.DAL.T_User();
public T_User()
{}
#region BasicMethod
public bool ValidatorUser(UserLogin.Model.T_User model)
{
return dal.ValidatorUser(model);
}
/// <summary>
/// 得到最大ID
/// </summary>
public int GetMaxId()
{
return dal.GetMaxId();
}
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(int Id)
{
return dal.Exists(Id);
}
/// <summary>
/// 增加一条数据
/// </summary>
public int Add(UserLogin.Model.T_User model)
{
return dal.Add(model);
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(UserLogin.Model.T_User model)
{
return dal.Update(model);
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(int Id)
{
return dal.Delete(Id);
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool DeleteList(string Idlist )
{
return dal.DeleteList(Idlist );
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public UserLogin.Model.T_User GetModel(int Id)
{
return dal.GetModel(Id);
}
/// <summary>
/// 获得前几行数据
/// </summary>
public DataSet GetList(int Top,string strWhere,string filedOrder)
{
return dal.GetList(Top,strWhere,filedOrder);
}
/// <summary>
/// 获得数据列表
/// </summary>
public List<UserLogin.Model.T_User> GetModelList(string strWhere)
{
DataSet ds = dal.GetList(strWhere);
return DataTableToList(ds.Tables[0]);
}
/// <summary>
/// 获得数据列表
/// </summary>
public List<UserLogin.Model.T_User> DataTableToList(DataTable dt)
{
List<UserLogin.Model.T_User> modelList = new List<UserLogin.Model.T_User>();
int rowsCount = dt.Rows.Count;
if (rowsCount > 0)
{
UserLogin.Model.T_User model;
for (int n = 0; n < rowsCount; n++)
{
model = dal.DataRowToModel(dt.Rows[n]);
if (model != null)
{
modelList.Add(model);
}
}
}
return modelList;
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public int GetRecordCount(string strWhere)
{
return dal.GetRecordCount(strWhere);
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
return dal.GetListByPage( strWhere, orderby, startIndex, endIndex);
}
/// <summary>
/// 分页获取数据列表
/// </summary>
//public DataSet GetList(int PageSize,int PageIndex,string strWhere)
//{
//return dal.GetList(PageSize,PageIndex,strWhere);
//}
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
DAL类:
/** 版本信息模板在安装目录下,可自行修改。
* T_User.cs
*
* 功 能: N/A
* 类 名: T_User
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2013/4/2 15:19:11 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using UserLogin.DataAccess;
namespace UserLogin.DAL
{
/// <summary>
/// 数据访问类:T_User
/// </summary>
public partial class T_User
{
public T_User()
{}
#region BasicMethod
public bool ValidatorUser(UserLogin.Model.T_User model)
{
bool result=false;
StringBuilder sb1 = new StringBuilder();
sb1.Append("SELECT COUNT(*) FROM T_User WHERE UserName=@username AND Password=@password");
SqlParameter[] parameters = {
new SqlParameter("@username", model.UserName),
new SqlParameter("@password", model.Password)};
object obj= DbHelperSQL.GetSingle(sb1.ToString(), parameters);
if (Convert.ToInt32(obj)!=0)
{
result = true;
}
return result;
}
/// <summary>
/// 得到最大ID
/// </summary>
public int GetMaxId()
{
return DbHelperSQL.GetMaxID("Id", "T_User");
}
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(int Id)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) from T_User");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@Id", SqlDbType.Int,4)
};
parameters[0].Value = Id;
return DbHelperSQL.Exists(strSql.ToString(),parameters);
}
/// <summary>
/// 增加一条数据
/// </summary>
public int Add(UserLogin.Model.T_User model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into T_User(");
strSql.Append("UserId,UserName,Password,RealName,Mobile,Department)");
strSql.Append(" values (");
strSql.Append("@UserId,@UserName,@Password,@RealName,@Mobile,@Department)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = {
new SqlParameter("@UserId", SqlDbType.VarChar,8),
new SqlParameter("@UserName", SqlDbType.VarChar,16),
new SqlParameter("@Password", SqlDbType.VarChar,16),
new SqlParameter("@RealName", SqlDbType.VarChar,16),
new SqlParameter("@Mobile", SqlDbType.VarChar,16),
new SqlParameter("@Department", SqlDbType.VarChar,32)};
parameters[0].Value = model.UserId;
parameters[1].Value = model.UserName;
parameters[2].Value = model.Password;
parameters[3].Value = model.RealName;
parameters[4].Value = model.Mobile;
parameters[5].Value = model.Department;
object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(UserLogin.Model.T_User model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("update T_User set ");
strSql.Append("UserId=@UserId,");
strSql.Append("UserName=@UserName,");
strSql.Append("Password=@Password,");
strSql.Append("RealName=@RealName,");
strSql.Append("Mobile=@Mobile,");
strSql.Append("Department=@Department");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@UserId", SqlDbType.VarChar,8),
new SqlParameter("@UserName", SqlDbType.VarChar,16),
new SqlParameter("@Password", SqlDbType.VarChar,16),
new SqlParameter("@RealName", SqlDbType.VarChar,16),
new SqlParameter("@Mobile", SqlDbType.VarChar,16),
new SqlParameter("@Department", SqlDbType.VarChar,32),
new SqlParameter("@Id", SqlDbType.Int,4)};
parameters[0].Value = model.UserId;
parameters[1].Value = model.UserName;
parameters[2].Value = model.Password;
parameters[3].Value = model.RealName;
parameters[4].Value = model.Mobile;
parameters[5].Value = model.Department;
parameters[6].Value = model.Id;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(int Id)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from T_User ");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@Id", SqlDbType.Int,4)
};
parameters[0].Value = Id;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteList(string Idlist )
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from T_User ");
strSql.Append(" where Id in ("+Idlist + ") ");
int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public UserLogin.Model.T_User GetModel(int Id)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select top 1 Id,UserId,UserName,Password,RealName,Mobile,Department from T_User ");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@Id", SqlDbType.Int,4)
};
parameters[0].Value = Id;
UserLogin.Model.T_User model=new UserLogin.Model.T_User();
DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
if(ds.Tables[0].Rows.Count>0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public UserLogin.Model.T_User DataRowToModel(DataRow row)
{
UserLogin.Model.T_User model=new UserLogin.Model.T_User();
if (row != null)
{
if(row["Id"]!=null && row["Id"].ToString()!="")
{
model.Id=int.Parse(row["Id"].ToString());
}
if(row["UserId"]!=null)
{
model.UserId=row["UserId"].ToString();
}
if(row["UserName"]!=null)
{
model.UserName=row["UserName"].ToString();
}
if(row["Password"]!=null)
{
model.Password=row["Password"].ToString();
}
if(row["RealName"]!=null)
{
model.RealName=row["RealName"].ToString();
}
if(row["Mobile"]!=null)
{
model.Mobile=row["Mobile"].ToString();
}
if(row["Department"]!=null)
{
model.Department=row["Department"].ToString();
}
}
return model;
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select Id,UserId,UserName,Password,RealName,Mobile,Department ");
strSql.Append(" FROM T_User ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 获得前几行数据
/// </summary>
public DataSet GetList(int Top,string strWhere,string filedOrder)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select ");
if(Top>0)
{
strSql.Append(" top "+Top.ToString());
}
strSql.Append(" Id,UserId,UserName,Password,RealName,Mobile,Department ");
strSql.Append(" FROM T_User ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
strSql.Append(" order by " + filedOrder);
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 获取记录总数
/// </summary>
public int GetRecordCount(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) FROM T_User ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString());
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("SELECT * FROM ( ");
strSql.Append(" SELECT ROW_NUMBER() OVER (");
if (!string.IsNullOrEmpty(orderby.Trim()))
{
strSql.Append("order by T." + orderby );
}
else
{
strSql.Append("order by T.Id desc");
}
strSql.Append(")AS Row, T.* from T_User T ");
if (!string.IsNullOrEmpty(strWhere.Trim()))
{
strSql.Append(" WHERE " + strWhere);
}
strSql.Append(" ) TT");
strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
return DbHelperSQL.Query(strSql.ToString());
}
/*
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
SqlParameter[] parameters = {
new SqlParameter("@tblName", SqlDbType.VarChar, 255),
new SqlParameter("@fldName", SqlDbType.VarChar, 255),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@PageIndex", SqlDbType.Int),
new SqlParameter("@IsReCount", SqlDbType.Bit),
new SqlParameter("@OrderType", SqlDbType.Bit),
new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
};
parameters[0].Value = "T_User";
parameters[1].Value = "Id";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}*/
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
DataAccess类:
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
namespace UserLogin.DataAccess
{
/// <summary>
/// 数据访问抽象基础类
/// Copyright (C) Maticsoft
/// </summary>
public abstract class DbHelperSQL
{
//数据库连接字符串(web.config来配置),多数据库可使用DbHelperSQLP来实现.
public static string connectionString = ConfigurationManager.ConnectionStrings["sqlservercon"].ConnectionString;
public DbHelperSQL()
{
}
#region 公用方法
/// <summary>
/// 判断是否存在某表的某个字段
/// </summary>
/// <param name="tableName">表名称</param>
/// <param name="columnName">列名称</param>
/// <returns>是否存在</returns>
public static bool ColumnExists(string tableName, string columnName)
{
string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
object res = GetSingle(sql);
if (res == null)
{
return false;
}
return Convert.ToInt32(res) > 0;
}
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString()); //也可能=0
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 表是否存在
/// </summary>
/// <param name="TableName"></param>
/// <returns></returns>
public static bool TabExists(string TableName)
{
string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
//string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
object obj = GetSingle(strsql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
public static bool Exists(string strSql, params SqlParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
#endregion
#region 执行简单SQL语句
/// <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 e;
}
}
}
}
public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static object ExecuteSqlGet(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSQL, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
public static object GetSingle(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, connection);
try
{
connection.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
/// <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;
}
}
public static DataSet Query(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region 执行带参数的SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
int indentity = 0;
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
foreach (SqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (SqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
// finally
// {
// cmd.Dispose();
// connection.Close();
// }
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, 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 = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
#endregion
#region 存储过程操作
/// <summary>
/// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader returnReader;
connection.Open();
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.CommandType = CommandType.StoredProcedure;
returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
return returnReader;
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.SelectCommand.CommandTimeout = Times;
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
if (parameter != null)
{
// 检查未分配值的输出参数,将其分配以DBNull.Value.
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
}
return command;
}
/// <summary>
/// 执行存储过程,返回影响的行数
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="rowsAffected">影响的行数</param>
/// <returns></returns>
public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
int result;
connection.Open();
SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
rowsAffected = command.ExecuteNonQuery();
result = (int)command.Parameters["ReturnValue"].Value;
//Connection.Close();
return result;
}
}
/// <summary>
/// 创建 SqlCommand 对象实例(用来返回一个整数值)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand 对象实例</returns>
private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, 4, ParameterDirection.ReturnValue,
false, 0, 0, string.Empty, DataRowVersion.Default, null));
return command;
}
#endregion
}
}
MODEL类:
/** 版本信息模板在安装目录下,可自行修改。
* T_User.cs
*
* 功 能: N/A
* 类 名: T_User
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2013/4/2 15:19:11 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace UserLogin.Model
{
/// <summary>
/// T_User:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public partial class T_User
{
public T_User()
{}
#region Model
private int _id;
private string _userid;
private string _username;
private string _password;
private string _realname;
private string _mobile;
private string _department;
/// <summary>
///
/// </summary>
public int Id
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
/// 用户编号
/// </summary>
public string UserId
{
set{ _userid=value;}
get{return _userid;}
}
/// <summary>
/// 用户名
/// </summary>
public string UserName
{
set{ _username=value;}
get{return _username;}
}
/// <summary>
/// 密码
/// </summary>
public string Password
{
set{ _password=value;}
get{return _password;}
}
/// <summary>
/// 用户姓名
/// </summary>
public string RealName
{
set{ _realname=value;}
get{return _realname;}
}
/// <summary>
/// 手机
/// </summary>
public string Mobile
{
set{ _mobile=value;}
get{return _mobile;}
}
/// <summary>
/// 所属部门
/// </summary>
public string Department
{
set{ _department=value;}
get{return _department;}
}
#endregion Model
}
}
Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细消息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="sqlservercon" connectionString="Data Source=PC-20130314PXQG;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=842674"/>
<add name="sqlservercon1" connectionString="Data Source=FZW-PC;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=yhb@163"/>
<add name="sqlservercon2" connectionString="Data Source=WJP-PC;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=yhb@163"/>
</connectionStrings>
</configuration>