首先介绍一下c#,也叫c shape,是由微软开发语言,它和java类似都是面向对象的编程语言,下面我将详细介绍使用c#编写一个小项目,可以记录自己的学习成果,也可以方便复习。
目录
1.创建项目骨架
2.首先编写工具类,
3.创建实体层
4.创建数据库访问层:
5.创建逻辑控制层
6.编写页面,验证功能
1.首先创建类库类似于下图的结构,当然也可以不如此,创建一下结构是为了分层。login是整个web项目的主题,下边存放一些asp,js,css等页面,YMBLL是界面层,YMDAL是数据层,YMModel是实体层,YMutility是工具层,下边存放一些用得到的工具类。
因为这是基础。
js相关工具类,用于控制界面跳转
///
/// 类说明:Assistant
/// 编 码 人:九千七
/// 联系方式:
/// 更新网站:[url=http://www.cckan.net/thread-655-1-1.html]http://www.cckan.net/thread-655-1-1.html[/url]
///
using System.Web;
namespace YM.Mutility
{
///
/// 客户端脚本输出
///
public class JsHelper
{
///
/// 弹出信息,并跳转指定页面。
///
public static void AlertAndRedirect(string message, string toURL)
{
string js = "";
HttpContext.Current.Response.Write(string.Format(js, message, toURL));
HttpContext.Current.Response.End();
}
///
/// 弹出信息,并返回历史页面
///
public static void AlertAndGoHistory(string message, int value)
{
string js = @"";
HttpContext.Current.Response.Write(string.Format(js, message, value));
HttpContext.Current.Response.End();
}
///
/// 直接跳转到指定的页面
///
public static void Redirect(string toUrl)
{
string js = @"";
HttpContext.Current.Response.Write(string.Format(js, toUrl));
}
///
/// 弹出信息 并指定到父窗口
///
public static void AlertAndParentUrl(string message, string toURL)
{
string js = "";
HttpContext.Current.Response.Write(string.Format(js, message, toURL));
}
///
/// 返回到父窗口
///
public static void ParentRedirect(string ToUrl)
{
string js = "";
HttpContext.Current.Response.Write(string.Format(js, ToUrl));
}
///
/// 返回历史页面
///
public static void BackHistory(int value)
{
string js = @"";
HttpContext.Current.Response.Write(string.Format(js, value));
HttpContext.Current.Response.End();
}
///
/// 弹出信息
///
public static void Alert(string message)
{
string js = "";
HttpContext.Current.Response.Write(string.Format(js, message));
}
///
/// 注册脚本块
///
public static void RegisterScriptBlock(System.Web.UI.Page page, string _ScriptString)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "scriptblock", "");
}
}
}
数据库相关工具类,封装了数据库连接与先关sql执行功能
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
//访问底层数据库
namespace YM.Mutility
{
public class MsSqlHelper
{
/*寻找物理数据库此处数据库的相关配置需要早web.config文件配置
public static readonly string connectionString = ConfigurationManager.ConnectionStrings["xiaobai"].ConnectionString;*/
//也可以使用一下代码来连接数据库
static string connectionString= "Data Source=xp;Initial Catalog=ExpressManager;Integrated Security=TRUE;Data Source = .;Initial Catalog =xiaobai;User ID = sa;Pwd = compal";
static SqlConnection conn;
#region 公用方法
public static int GetMaxID(string FieldName, string TableName)
{
conn = new SqlConnection(connString);
conn.Open();
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)
{ conn = new SqlConnection(connString);
conn.Open();
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)
{ conn = new SqlConnection(connString);
conn.Open();
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语句
///
/// 执行SQL语句,返回影响的记录数
///
/// SQL语句
/// 影响的记录数
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 (SqlException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
///
/// 执行SQL语句,设置命令的执行等待时间
///
///
///
///
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 (SqlException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// 多条SQL语句
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
///
/// 执行带一个存储过程参数的的SQL语句。
///
/// SQL语句
/// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加
/// 影响的记录数
public static int ExecuteSql(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
///
/// 执行带一个存储过程参数的的SQL语句。
///
/// SQL语句
/// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加
/// 影响的记录数
public static object ExecuteSqlGet(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
SqlParameter myParameter = new 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 (SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
///
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
///
/// SQL语句
/// 图像字节,数据库的字段类型为image的情况
/// 影响的记录数
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSQL, connection);
SqlParameter myParameter = new SqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
///
/// 执行一条计算查询结果语句,返回查询结果(object)。
///
/// 计算查询结果语句
/// 查询结果(object)
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 (SqlException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
}
///
/// 执行查询语句,返回SqlDataReader(使用该方法切记要手工关闭SqlDataReader和连接)
///
/// 查询语句
/// SqlDataReader
public static SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, connection);
try
{
connection.Open();
SqlDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (SqlException e)
{
throw new Exception(e.Message);
}
//finally //不能在此关闭,否则,返回的对象将无法使用
//{
// cmd.Dispose();
// connection.Close();
//}
}
///
/// 执行查询语句,返回DataSet
///
/// 查询语句
/// DataSet
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 (SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
public static DataSet Query(string SQLString, string TableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, TableName);
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
///
/// 执行查询语句,返回DataSet,设置命令的执行等待时间
///
///
///
///
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 (SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region 执行带参数的SQL语句
///
/// 执行SQL语句,返回影响的记录数
///
/// SQL语句
/// 影响的记录数
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 (SqlException E)
{
throw new Exception(E.Message);
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])
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;
}
}
}
}
///
/// 执行一条计算查询结果语句,返回查询结果(object)。
///
/// 计算查询结果语句
/// 查询结果(object)
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 (SqlException e)
{
throw new Exception(e.Message);
}
}
}
}
///
/// 执行查询语句,返回SqlDataReader (使用该方法切记要手工关闭SqlDataReader和连接)
///
/// 查询语句
/// SqlDataReader
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();
cmd.Parameters.Clear();
return myReader;
}
catch (SqlException e)
{
throw new Exception(e.Message);
}
//finally //不能在此关闭,否则,返回的对象将无法使用
//{
// cmd.Dispose();
// connection.Close();
//}
}
///
/// 执行查询语句,返回DataSet
///
/// 查询语句
/// DataSet
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 (SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
public 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 存储过程操作
///
/// 执行存储过程 (使用该方法切记要手工关闭SqlDataReader和连接)
///
/// 存储过程名
/// 存储过程参数
/// SqlDataReader
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();
//Connection.Close(); 不能在此关闭,否则,返回的对象将无法使用
return returnReader;
}
///
/// 执行存储过程
///
/// 存储过程名
/// 存储过程参数
/// 结果中第一行第一列
public static string RunProc(string storedProcName, IDataParameter[] parameters)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string StrValue;
connection.Open();
SqlCommand cmd;
cmd = BuildQueryCommand(connection, storedProcName, parameters);
StrValue = cmd.ExecuteScalar().ToString();
connection.Close();
return StrValue;
}
}
///
/// 执行存储过程
///
/// 存储过程名
/// 存储过程参数
/// DataSet结果中的表名
/// DataSet
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;
}
}
///
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
///
/// 数据库连接
/// 存储过程名
/// 存储过程参数
/// SqlCommand
public 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;
}
///
/// 执行存储过程,返回影响的行数
///
/// 存储过程名
/// 存储过程参数
/// 影响的行数
///
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;
}
}
///
/// 创建 SqlCommand 对象实例(用来返回一个整数值)
///
/// 存储过程名
/// 存储过程参数
/// SqlCommand 对象实例
public 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;
}
///
/// 执行SQL语句
///
/// 存储过程名
/// 存储过程参数
/// 结果中第一行第一列
public static string RunSql(string query)
{
string str;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
try
{
connection.Open();
//str = (cmd.ExecuteScalar().ToString() == "") ? "" : cmd.ExecuteScalar().ToString();
str = "";
if (cmd.ExecuteScalar() == null)
{
str = "";
}
else
{
str = cmd.ExecuteScalar().ToString();
}
return str;
}
catch (SqlException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
#endregion
}
}
session工具类
using System;
using System.Web;
namespace YM.Mutility
{
#region Session操作助手类-SessionHelper
///
/// Session操作助手类
///
public class SessionHelper
{
static SessionHelper() { HttpContext.Current.Session.Timeout = 30; }
///
/// 设置一个Session
///
/// Session的Key值
/// Session的Value值
public static void SetSession(string key, object value)
{
HttpContext.Current.Session.Remove(key);
HttpContext.Current.Session.Add(key, value);
}
///
/// 移除Session
///
/// Session的Key值
public static void RemoveSession(string key)
{
HttpContext.Current.Session.Remove(key);
}
///
/// 移除所有Session
///
public static void RemoveAllSession()
{
HttpContext.Current.Session.RemoveAll();
}
///
/// 获取Session值
///
/// Session的Key值
/// Session的Value值
public static object GetSesstion(string key)
{
return HttpContext.Current.Session[key];
}
///
/// 获取Session(泛型)
///
/// 希望获得的类型
/// Session的Key值
/// Session的Value值
public static T GetSesstion(string key)
{
return ((T)(HttpContext.Current.Session[key]));
}
///
/// 设置Session超时时间
///
/// 超时时间(单位:分)
public static void SetTimeout(int timeout)
{
HttpContext.Current.Session.Timeout = timeout;
}
///
/// 获取session超时时间
///
///
public static int GetTimeout()
{
return HttpContext.Current.Session.Timeout;
}
}
#endregion
}
实体层对应数据库里的表以及列,
附上数据库创建命令
USE [xiaobai]
GO
/****** Object: Table [dbo].[t_user] Script Date: 2021/3/15 22:32:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[t_user](
[id] [int] IDENTITY(1,1) NOT NULL,
[username] [varchar](50) NULL,
[password] [varchar](50) NULL,
[name] [varchar](50) NULL,
[address] [varchar](50) NULL,
[sex] [varchar](50) NULL,
[mobile] [varchar](50) NULL,
[email] [varchar](50) NULL,
[qq] [varchar](50) NULL,
[state] [varchar](50) NULL,
[adddate] [varchar](50) NULL,
CONSTRAINT [PK_t_user] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
还有数据库数据截图
该例仅使用用户表进行用户登录功能,所以就写一个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YM.Model
{
public class User
{
private int id;
private string username;
private string password;
private string name;
private string address;
private string sex;
private string mobile;
private string email;
private string qq;
private string state;
private string adddate;
public int Id { get => id; set => id = value; }
public string Username { get => username; set => username = value; }
public string Name { get => name; set => name = value; }
public string Address { get => address; set => address = value; }
public string Sex { get => sex; set => sex = value; }
public string Mobile { get => mobile; set => mobile = value; }
public string Email { get => email; set => email = value; }
public string Qq { get => qq; set => qq = value; }
public string Password { get => password; set => password = value; }
public string State { get => state; set => state = value; }
public string Adddate { get => adddate; set => adddate = value; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
//using YM.Model;
//数据库访问层
namespace YM.DAL
{
///
/// 用户数据访问层
///
public class User
{
///
/// 添加用户
///
///
///
public static bool add(YM.Model.User user)
{
bool result = false;
string strsql = "insert into t_user (username,password,name,address,sex,mobile,email,qq,state,adddate) values('" +
user.Username + "','" + user.Password + "','" + user.Name + "','" +
user.Address + "','" + user.Sex + "','" + user.Mobile + "','" +
user.Email + "','" + user.Qq + "','" + user.State + "','" + user.Adddate + "');";
int i = YM.Mutility.MsSqlHelper.ExecuteSql(strsql);
if (i > 0)
{
result = true;
}
return result;
}
///
/// 判断用户是否重复
///
///
///
public static bool Search(string username)
{
bool result = true;
string strsql = "select * from t_user where username='" + username + "';";
DataTable dateTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[0];
if (dateTable.Rows.Count == 0)
{
result = true;
}
else
{
result = false;
}
return result;
}
///
/// 登录
///
///
///
///
public static bool Login(string username, string password)
{
bool result = false;
string strsql = "select * from t_user where username='" + username + "' and password='" + password + "'";
DataTable dateTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[0];
if (dateTable.Rows.Count != 0)
{
result = true;
}
else
{
result = false;
}
return result;
}
///
/// 查找队列
///
///
public static List list()
{
string strsql = "select * from t_user order by id desc";
DataTable dataTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[0];
return Dttolist(dataTable);
}
///
/// 循环赋值
///
///
///
public static List Dttolist(DataTable dt)
{
List list = new List();
for(int i=0;i
/// 找到数据赋值给实例对象
///
///
///
public static YM.Model.User GetUser(int id)
{
YM.Model.User user = new Model.User();
string strsql = "select * from t_user where id=" + id + "";
DataTable dataTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[0];
if(dataTable.Rows.Count!=0)
{
user.Id = int.Parse(dataTable.Rows[0]["id"].ToString());
user.Username = dataTable.Rows[0]["username"].ToString();
user.Password = dataTable.Rows[0]["password"].ToString();
user.Name = dataTable.Rows[0]["Name"].ToString();
user.Address = dataTable.Rows[0]["Address"].ToString();
user.Sex = dataTable.Rows[0]["Sex"].ToString();
user.Mobile = dataTable.Rows[0]["Mobile"].ToString();
user.Email = dataTable.Rows[0]["Email"].ToString();
user.Qq = dataTable.Rows[0]["Qq"].ToString();
user.State = dataTable.Rows[0]["State"].ToString();
user.Adddate = dataTable.Rows[0]["Adddate"].ToString();
}
return user;
}
public static YM.Model.User GetUser1(string username)
{
YM.Model.User user = new Model.User();
string strsql = "select * from t_user where username='" + username + "'";
DataTable dataTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[0];
if (dataTable.Rows.Count != 0)
{
user.Id = int.Parse(dataTable.Rows[0]["id"].ToString());
user.Username = dataTable.Rows[0]["username"].ToString();
user.Password = dataTable.Rows[0]["password"].ToString();
user.Name = dataTable.Rows[0]["Name"].ToString();
user.Address = dataTable.Rows[0]["Address"].ToString();
user.Sex = dataTable.Rows[0]["Sex"].ToString();
user.Mobile = dataTable.Rows[0]["Mobile"].ToString();
user.Email = dataTable.Rows[0]["Email"].ToString();
user.Qq = dataTable.Rows[0]["Qq"].ToString();
user.State = dataTable.Rows[0]["State"].ToString();
user.Adddate = dataTable.Rows[0]["Adddate"].ToString();
}
return user;
}
public static bool del(int id)
{
bool result = false;
string sqlstr = "delete from t_user where id=" + id + "";
int i = YM.Mutility.MsSqlHelper.ExecuteSql(sqlstr);
if(i>0)
{
result = true;
}
return result;
}
public static bool Update(YM.Model.User user)
{
bool result = false;
string sqlstr = "update t_user set username='" + user.Username +"',password='"+user.Password+
"',address='" + user.Address +"',email='" + user.Email + "' where id=" + user.Id + ";";
int i = YM.Mutility.MsSqlHelper.ExecuteSql(sqlstr);
if (i > 0)
{
result = true;
}
return result;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YM.BLL
{///
/// 用户的业务层
///
public class User
{
///
/// 用户在业务层添加方法,调用数据库访问层
///
///
///
public static bool add(YM.Model.User user)
{
return YM.DAL.User.add(user);
}
public static bool Search(string username)
{
return YM.DAL.User.Search(username);
}
public static bool Login(string username, string password)
{
return YM.DAL.User.Login(username, password);
}
public static List list()
{
return YM.DAL.User.list();
}
public static bool del(int id)
{
return YM.DAL.User.del(id);
}
public static bool update(YM.Model.User user)
{
return YM.DAL.User.Update(user);
}
public static YM.Model.User GetUser(int id)
{
return YM.DAL.User.GetUser(id);
}
public static YM.Model.User GetUser1(string id)
{
return YM.DAL.User.GetUser1(id);
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
后台验证
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string username = this.username.Text;
string password = this.password.Text;
//判断登录
if(YM.BLL.User.Login(username,password)==true)
{
YM.Model.User user = YM.BLL.User.GetUser1(username);//获取user的值
if (user.State.Equals("1"))
{
YM.Mutility.SessionHelper.SetSession("user", user);
YM.Mutility.JsHelper.AlertAndRedirect("登陆成功,", "user/index.aspx?");
}
}
else
{
YM.Mutility.JsHelper.AlertAndRedirect("登陆失败,请注册,", "reg.aspx");
}
}
}
至此使用c#的一个用户登录功能就已经全部完成了。注意要点就是本次没有写注册功能,就需要在数据库中创建一个数据进行验证了。总结要点就是使用分层思想可以将你的整个项目的架构更清晰,后期维护容易。