首先介绍一下c#,也叫c shape,是由微软开发语言,它和java类似都是面向对象的编程语言,下面我将详细介绍使用c#编写一个小项目,可以记录自己的学习成果,也可以方便复习。
目录
1.创建项目骨架
1.首先创建类库类似于下图的结构,当然也可以不如此,创建一下结构是为了分层。login是整个web项目的主题,下边存放一些asp,js,css等页面,YMBLL是界面层,YMDAL是数据层,YMModel是实体层,YMutility是工具层,下边存放一些用得到的工具类。

2.首先编写工具类,
因为这是基础。
js相关工具类,用于控制界面跳转
-
/// <summary>
-
/// 类说明:Assistant
-
/// 编 码 人:九千七
-
/// 联系方式:
-
/// 更新网站:[url=http://www.cckan.net/thread-655-1-1.html]http://www.cckan.net/thread-655-1-1.html[/url]
-
/// </summary>
-
using System.Web;
-
-
namespace
YM.Mutility
-
{
-
/// <summary>
-
/// 客户端脚本输出
-
/// </summary>
-
public
class
JsHelper
-
{
-
/// <summary>
-
/// 弹出信息,并跳转指定页面。
-
/// </summary>
-
public static void AlertAndRedirect(string message, string toURL)
-
{
-
string js =
"<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
-
HttpContext.Current.Response.Write(
string.Format(js, message, toURL));
-
HttpContext.Current.Response.End();
-
}
-
-
/// <summary>
-
/// 弹出信息,并返回历史页面
-
/// </summary>
-
public static void AlertAndGoHistory(string message, int value)
-
{
-
string js =
@"<Script language='JavaScript'>alert('{0}');history.go({1});</Script>";
-
HttpContext.Current.Response.Write(
string.Format(js, message,
value));
-
HttpContext.Current.Response.End();
-
}
-
-
/// <summary>
-
/// 直接跳转到指定的页面
-
/// </summary>
-
public static void Redirect(string toUrl)
-
{
-
string js =
@"<script language=javascript>window.location.replace('{0}')</script>";
-
HttpContext.Current.Response.Write(
string.Format(js, toUrl));
-
}
-
-
/// <summary>
-
/// 弹出信息 并指定到父窗口
-
/// </summary>
-
public static void AlertAndParentUrl(string message, string toURL)
-
{
-
string js =
"<script language=javascript>alert('{0}');window.top.location.replace('{1}')</script>";
-
HttpContext.Current.Response.Write(
string.Format(js, message, toURL));
-
}
-
-
/// <summary>
-
/// 返回到父窗口
-
/// </summary>
-
public static void ParentRedirect(string ToUrl)
-
{
-
string js =
"<script language=javascript>window.top.location.replace('{0}')</script>";
-
HttpContext.Current.Response.Write(
string.Format(js, ToUrl));
-
}
-
-
/// <summary>
-
/// 返回历史页面
-
/// </summary>
-
public static void BackHistory(int value)
-
{
-
string js =
@"<Script language='JavaScript'>history.go({0});</Script>";
-
HttpContext.Current.Response.Write(
string.Format(js,
value));
-
HttpContext.Current.Response.End();
-
}
-
-
/// <summary>
-
/// 弹出信息
-
/// </summary>
-
public static void Alert(string message)
-
{
-
string js =
"<script language=javascript>alert('{0}');</script>";
-
HttpContext.Current.Response.Write(
string.Format(js, message));
-
}
-
-
/// <summary>
-
/// 注册脚本块
-
/// </summary>
-
public static void RegisterScriptBlock(System.Web.UI.Page page, string _ScriptString)
-
{
-
page.ClientScript.RegisterStartupScript(page.GetType(),
"scriptblock",
"<script type='text/javascript'>" + _ScriptString +
"</script>");
-
}
-
}
-
}
数据库相关工具类,封装了数据库连接与先关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语句
-
-
/// <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 (SqlException E)
-
{
-
connection.Close();
-
throw
new Exception(E.Message);
-
}
-
}
-
}
-
}
-
-
/// <summary>
-
/// 执行SQL语句,设置命令的执行等待时间
-
/// </summary>
-
/// <param name="SQLString"></param>
-
/// <param name="Times"></param>
-
/// <returns></returns>
-
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);
-
}
-
}
-
}
-
}
-
-
/// <summary>
-
/// 执行多条SQL语句,实现数据库事务。
-
/// </summary>
-
/// <param name="SQLStringList">多条SQL语句</param>
-
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);
-
}
-
}
-
}
-
-
/// <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);
-
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();
-
}
-
}
-
}
-
-
/// <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);
-
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();
-
}
-
}
-
}
-
-
/// <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);
-
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();
-
}
-
}
-
}
-
-
/// <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 (SqlException e)
-
{
-
connection.Close();
-
throw
new Exception(e.Message);
-
}
-
}
-
}
-
}
-
-
/// <summary>
-
/// 执行查询语句,返回SqlDataReader(使用该方法切记要手工关闭SqlDataReader和连接)
-
/// </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();
-
return myReader;
-
}
-
catch (SqlException e)
-
{
-
throw
new Exception(e.Message);
-
}
-
//finally //不能在此关闭,否则,返回的对象将无法使用
-
//{
-
// cmd.Dispose();
-
// connection.Close();
-
//}
-
}
-
-
/// <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 (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;
-
}
-
}
-
-
/// <summary>
-
/// 执行查询语句,返回DataSet,设置命令的执行等待时间
-
/// </summary>
-
/// <param name="SQLString"></param>
-
/// <param name="Times"></param>
-
/// <returns></returns>
-
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语句
-
-
/// <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 (SqlException E)
-
{
-
throw
new Exception(E.Message);
-
}
-
}
-
}
-
}
-
-
/// <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>
-
/// 执行一条计算查询结果语句,返回查询结果(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 (SqlException e)
-
{
-
throw
new Exception(e.Message);
-
}
-
}
-
}
-
}
-
-
/// <summary>
-
/// 执行查询语句,返回SqlDataReader (使用该方法切记要手工关闭SqlDataReader和连接)
-
/// </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();
-
cmd.Parameters.Clear();
-
return myReader;
-
}
-
catch (SqlException e)
-
{
-
throw
new Exception(e.Message);
-
}
-
//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 (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 存储过程操作
-
-
/// <summary>
-
/// 执行存储过程 (使用该方法切记要手工关闭SqlDataReader和连接)
-
/// </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();
-
//Connection.Close(); 不能在此关闭,否则,返回的对象将无法使用
-
return returnReader;
-
-
}
-
-
/// <summary>
-
/// 执行存储过程
-
/// </summary>
-
/// <param name="storedProcName">存储过程名</param>
-
/// <param name="parameters">存储过程参数</param>
-
/// <returns>结果中第一行第一列</returns>
-
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;
-
}
-
}
-
-
/// <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>
-
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;
-
}
-
-
/// <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>
-
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;
-
}
-
-
/// <summary>
-
/// 执行SQL语句
-
/// </summary>
-
/// <param name="storedProcName">存储过程名</param>
-
/// <param name="parameters">存储过程参数</param>
-
/// <returns>结果中第一行第一列</returns>
-
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
-
-
/// <summary>
-
/// Session操作助手类
-
/// </summary>
-
public
class
SessionHelper
-
{
-
static SessionHelper() { HttpContext.Current.Session.Timeout =
30; }
-
-
/// <summary>
-
/// 设置一个Session
-
/// </summary>
-
/// <param name="key">Session的Key值</param>
-
/// <param name="value">Session的Value值</param>
-
public static void SetSession(string key, object value)
-
{
-
HttpContext.Current.Session.Remove(key);
-
HttpContext.Current.Session.Add(key,
value);
-
}
-
-
/// <summary>
-
/// 移除Session
-
/// </summary>
-
/// <param name="key">Session的Key值</param>
-
public static void RemoveSession(string key)
-
{
-
HttpContext.Current.Session.Remove(key);
-
}
-
-
/// <summary>
-
/// 移除所有Session
-
/// </summary>
-
public static void RemoveAllSession()
-
{
-
HttpContext.Current.Session.RemoveAll();
-
}
-
-
/// <summary>
-
/// 获取Session值
-
/// </summary>
-
/// <param name="key">Session的Key值</param>
-
/// <returns>Session的Value值</returns>
-
public static object GetSesstion(string key)
-
{
-
return HttpContext.Current.Session[key];
-
}
-
-
/// <summary>
-
/// 获取Session(泛型)
-
/// </summary>
-
/// <typeparam name="T">希望获得的类型</typeparam>
-
/// <param name="key">Session的Key值</param>
-
/// <returns>Session的Value值</returns>
-
public static T GetSesstion<T>(string key)
-
{
-
return ((T)(HttpContext.Current.Session[key]));
-
}
-
-
/// <summary>
-
/// 设置Session超时时间
-
/// </summary>
-
/// <param name="timeout">超时时间(单位:分)</param>
-
public static void SetTimeout(int timeout)
-
{
-
HttpContext.Current.Session.Timeout = timeout;
-
}
-
-
-
/// <summary>
-
/// 获取session超时时间
-
/// </summary>
-
/// <returns></returns>
-
public static int GetTimeout()
-
{
-
return HttpContext.Current.Session.Timeout;
-
}
-
}
-
-
#endregion
-
}
3.创建实体层
实体层对应数据库里的表以及列,
附上数据库创建命令
-
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; }
-
}
-
}
4.创建数据库访问层:
-
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
-
{
-
/// <summary>
-
/// 用户数据访问层
-
/// </summary>
-
public
class
User
-
{
-
/// <summary>
-
/// 添加用户
-
/// </summary>
-
/// <param name="user"></param>
-
/// <returns></returns>
-
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;
-
}
-
/// <summary>
-
/// 判断用户是否重复
-
/// </summary>
-
/// <param name="username"></param>
-
/// <returns></returns>
-
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;
-
}
-
/// <summary>
-
/// 登录
-
/// </summary>
-
/// <param name="username"></param>
-
/// <param name="password"></param>
-
/// <returns></returns>
-
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;
-
}
-
/// <summary>
-
/// 查找队列
-
/// </summary>
-
/// <returns></returns>
-
public
static List<YM.Model.User> list()
-
{
-
string strsql =
"select * from t_user order by id desc";
-
DataTable dataTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[
0];
-
return Dttolist(dataTable);
-
}
-
/// <summary>
-
/// 循环赋值
-
/// </summary>
-
/// <param name="dt"></param>
-
/// <returns></returns>
-
public
static List<YM.Model.User> Dttolist(DataTable dt)
-
{
-
List<YM.Model.User> list =
new List<Model.User>();
-
for(
int i=
0;i<dt.Rows.Count; i++)
-
{
-
YM.Model.User user =
new Model.User();
-
user = GetUser(
int.Parse(dt.Rows[i][
"id"].ToString()));
-
list.Add(user);
-
}
-
return list;
-
}
-
/// <summary>
-
/// 找到数据赋值给实例对象
-
/// </summary>
-
/// <param name="id"></param>
-
/// <returns></returns>
-
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;
-
}
-
}
-
}
5.创建逻辑控制层
-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
using System.Threading.Tasks;
-
-
namespace
YM.BLL
-
{
/// <summary>
-
/// 用户的业务层
-
/// </summary>
-
public
class
User
-
{
-
/// <summary>
-
/// 用户在业务层添加方法,调用数据库访问层
-
/// </summary>
-
/// <param name="user"></param>
-
/// <returns></returns>
-
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<YM.Model.User> 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);
-
}
-
}
-
}
6.编写页面,验证功能
-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
-
-
-
-
<!DOCTYPE html>
-
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head runat="server">
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
<title>
</title>
-
<style type="text/css">
-
.auto-style3 {
-
margin-bottom:
0px;
-
}
-
</style>
-
</head>
-
<body>
-
<form id="form1" runat="server">
-
<div>
-
-
<table align="center" width="200px">
<tr>
<td colspan="2">用户名:
</td>
<td>
-
<asp:TextBox ID="username" runat="server">
</asp:TextBox>
-
</td>
</tr>
-
<tr>
<td colspan="2">密码:
</td>
<td>
-
<asp:TextBox ID="password" runat="server">
</asp:TextBox>
-
</td>
</tr>
-
<tr>
<td>
-
<asp:Button ID="Button1" runat="server" Text="登录" OnClick="Button1_Click" />
-
</td>
-
</tr>
-
</table>
-
-
</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;
-
-
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#的一个用户登录功能就已经全部完成了。注意要点就是本次没有写注册功能,就需要在数据库中创建一个数据进行验证了。总结要点就是使用分层思想可以将你的整个项目的架构更清晰,后期维护容易。
转载:https://blog.csdn.net/weixin_42145499/article/details/114852421
查看评论