飞道的博客

基于c#的三层架构实现注册登录功能模块

720人阅读  评论(0)

       首先介绍一下c#,也叫c shape,是由微软开发语言,它和java类似都是面向对象的编程语言,下面我将详细介绍使用c#编写一个小项目,可以记录自己的学习成果,也可以方便复习。

目录

1.创建项目骨架

2.首先编写工具类,

3.创建实体层

4.创建数据库访问层:

5.创建逻辑控制层

6.编写页面,验证功能


1.创建项目骨架

1.首先创建类库类似于下图的结构,当然也可以不如此,创建一下结构是为了分层。login是整个web项目的主题,下边存放一些asp,js,css等页面,YMBLL是界面层,YMDAL是数据层,YMModel是实体层,YMutility是工具层,下边存放一些用得到的工具类。

2.首先编写工具类,

因为这是基础。

js相关工具类,用于控制界面跳转


  
  1. /// <summary>
  2. /// 类说明:Assistant
  3. /// 编 码 人:九千七
  4. /// 联系方式:
  5. /// 更新网站:[url=http://www.cckan.net/thread-655-1-1.html]http://www.cckan.net/thread-655-1-1.html[/url]
  6. /// </summary>
  7. using System.Web;
  8. namespace YM.Mutility
  9. {
  10. /// <summary>
  11. /// 客户端脚本输出
  12. /// </summary>
  13. public class JsHelper
  14. {
  15. /// <summary>
  16. /// 弹出信息,并跳转指定页面。
  17. /// </summary>
  18. public static void AlertAndRedirect(string message, string toURL)
  19. {
  20. string js = "<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
  21. HttpContext.Current.Response.Write( string.Format(js, message, toURL));
  22. HttpContext.Current.Response.End();
  23. }
  24. /// <summary>
  25. /// 弹出信息,并返回历史页面
  26. /// </summary>
  27. public static void AlertAndGoHistory(string message, int value)
  28. {
  29. string js = @"<Script language='JavaScript'>alert('{0}');history.go({1});</Script>";
  30. HttpContext.Current.Response.Write( string.Format(js, message, value));
  31. HttpContext.Current.Response.End();
  32. }
  33. /// <summary>
  34. /// 直接跳转到指定的页面
  35. /// </summary>
  36. public static void Redirect(string toUrl)
  37. {
  38. string js = @"<script language=javascript>window.location.replace('{0}')</script>";
  39. HttpContext.Current.Response.Write( string.Format(js, toUrl));
  40. }
  41. /// <summary>
  42. /// 弹出信息 并指定到父窗口
  43. /// </summary>
  44. public static void AlertAndParentUrl(string message, string toURL)
  45. {
  46. string js = "<script language=javascript>alert('{0}');window.top.location.replace('{1}')</script>";
  47. HttpContext.Current.Response.Write( string.Format(js, message, toURL));
  48. }
  49. /// <summary>
  50. /// 返回到父窗口
  51. /// </summary>
  52. public static void ParentRedirect(string ToUrl)
  53. {
  54. string js = "<script language=javascript>window.top.location.replace('{0}')</script>";
  55. HttpContext.Current.Response.Write( string.Format(js, ToUrl));
  56. }
  57. /// <summary>
  58. /// 返回历史页面
  59. /// </summary>
  60. public static void BackHistory(int value)
  61. {
  62. string js = @"<Script language='JavaScript'>history.go({0});</Script>";
  63. HttpContext.Current.Response.Write( string.Format(js, value));
  64. HttpContext.Current.Response.End();
  65. }
  66. /// <summary>
  67. /// 弹出信息
  68. /// </summary>
  69. public static void Alert(string message)
  70. {
  71. string js = "<script language=javascript>alert('{0}');</script>";
  72. HttpContext.Current.Response.Write( string.Format(js, message));
  73. }
  74. /// <summary>
  75. /// 注册脚本块
  76. /// </summary>
  77. public static void RegisterScriptBlock(System.Web.UI.Page page, string _ScriptString)
  78. {
  79. page.ClientScript.RegisterStartupScript(page.GetType(), "scriptblock", "<script type='text/javascript'>" + _ScriptString + "</script>");
  80. }
  81. }
  82. }

数据库相关工具类,封装了数据库连接与先关sql执行功能


  
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Specialized;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. //访问底层数据库
  8. namespace YM.Mutility
  9. {
  10. public class MsSqlHelper
  11. {
  12. /*寻找物理数据库此处数据库的相关配置需要早web.config文件配置
  13. public static readonly string connectionString = ConfigurationManager.ConnectionStrings["xiaobai"].ConnectionString;*/
  14. //也可以使用一下代码来连接数据库
  15. static string connectionString= "Data Source=xp;Initial Catalog=ExpressManager;Integrated Security=TRUE;Data Source = .;Initial Catalog =xiaobai;User ID = sa;Pwd = compal";
  16. static SqlConnection conn;
  17. #region 公用方法
  18. public static int GetMaxID(string FieldName, string TableName)
  19. {
  20. conn = new SqlConnection(connString);
  21. conn.Open();
  22. string strsql = "select max(" + FieldName + ")+1 from " + TableName;
  23. object obj = GetSingle(strsql);
  24. if (obj == null)
  25. {
  26. return 1;
  27. }
  28. else
  29. {
  30. return int.Parse(obj.ToString());
  31. }
  32. }
  33. public static bool Exists(string strSql)
  34. { conn = new SqlConnection(connString);
  35. conn.Open();
  36. object obj = GetSingle(strSql);
  37. int cmdresult;
  38. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  39. {
  40. cmdresult = 0;
  41. }
  42. else
  43. {
  44. cmdresult = int.Parse(obj.ToString());
  45. }
  46. if (cmdresult == 0)
  47. {
  48. return false;
  49. }
  50. else
  51. {
  52. return true;
  53. }
  54. }
  55. public static bool Exists(string strSql, params SqlParameter[] cmdParms)
  56. { conn = new SqlConnection(connString);
  57. conn.Open();
  58. object obj = GetSingle(strSql, cmdParms);
  59. int cmdresult;
  60. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  61. {
  62. cmdresult = 0;
  63. }
  64. else
  65. {
  66. cmdresult = int.Parse(obj.ToString());
  67. }
  68. if (cmdresult == 0)
  69. {
  70. return false;
  71. }
  72. else
  73. {
  74. return true;
  75. }
  76. }
  77. #endregion
  78. #region 执行简单SQL语句
  79. /// <summary>
  80. /// 执行SQL语句,返回影响的记录数
  81. /// </summary>
  82. /// <param name="SQLString">SQL语句</param>
  83. /// <returns>影响的记录数</returns>
  84. public static int ExecuteSql(string SQLString)
  85. {
  86. using (SqlConnection connection = new SqlConnection(connectionString))
  87. {
  88. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  89. {
  90. try
  91. {
  92. connection.Open();
  93. int rows = cmd.ExecuteNonQuery();
  94. return rows;
  95. }
  96. catch (SqlException E)
  97. {
  98. connection.Close();
  99. throw new Exception(E.Message);
  100. }
  101. }
  102. }
  103. }
  104. /// <summary>
  105. /// 执行SQL语句,设置命令的执行等待时间
  106. /// </summary>
  107. /// <param name="SQLString"></param>
  108. /// <param name="Times"></param>
  109. /// <returns></returns>
  110. public static int ExecuteSqlByTime(string SQLString, int Times)
  111. {
  112. using (SqlConnection connection = new SqlConnection(connectionString))
  113. {
  114. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  115. {
  116. try
  117. {
  118. connection.Open();
  119. cmd.CommandTimeout = Times;
  120. int rows = cmd.ExecuteNonQuery();
  121. return rows;
  122. }
  123. catch (SqlException E)
  124. {
  125. connection.Close();
  126. throw new Exception(E.Message);
  127. }
  128. }
  129. }
  130. }
  131. /// <summary>
  132. /// 执行多条SQL语句,实现数据库事务。
  133. /// </summary>
  134. /// <param name="SQLStringList">多条SQL语句</param>
  135. public static void ExecuteSqlTran(ArrayList SQLStringList)
  136. {
  137. using (SqlConnection conn = new SqlConnection(connectionString))
  138. {
  139. conn.Open();
  140. SqlCommand cmd = new SqlCommand();
  141. cmd.Connection = conn;
  142. SqlTransaction tx = conn.BeginTransaction();
  143. cmd.Transaction = tx;
  144. try
  145. {
  146. for ( int n = 0; n < SQLStringList.Count; n++)
  147. {
  148. string strsql = SQLStringList[n].ToString();
  149. if (strsql.Trim().Length > 1)
  150. {
  151. cmd.CommandText = strsql;
  152. cmd.ExecuteNonQuery();
  153. }
  154. }
  155. tx.Commit();
  156. }
  157. catch (SqlException E)
  158. {
  159. tx.Rollback();
  160. throw new Exception(E.Message);
  161. }
  162. }
  163. }
  164. /// <summary>
  165. /// 执行带一个存储过程参数的的SQL语句。
  166. /// </summary>
  167. /// <param name="SQLString">SQL语句</param>
  168. /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
  169. /// <returns>影响的记录数</returns>
  170. public static int ExecuteSql(string SQLString, string content)
  171. {
  172. using (SqlConnection connection = new SqlConnection(connectionString))
  173. {
  174. SqlCommand cmd = new SqlCommand(SQLString, connection);
  175. SqlParameter myParameter = new SqlParameter( "@content", SqlDbType.NText);
  176. myParameter.Value = content;
  177. cmd.Parameters.Add(myParameter);
  178. try
  179. {
  180. connection.Open();
  181. int rows = cmd.ExecuteNonQuery();
  182. return rows;
  183. }
  184. catch (SqlException E)
  185. {
  186. throw new Exception(E.Message);
  187. }
  188. finally
  189. {
  190. cmd.Dispose();
  191. connection.Close();
  192. }
  193. }
  194. }
  195. /// <summary>
  196. /// 执行带一个存储过程参数的的SQL语句。
  197. /// </summary>
  198. /// <param name="SQLString">SQL语句</param>
  199. /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
  200. /// <returns>影响的记录数</returns>
  201. public static object ExecuteSqlGet(string SQLString, string content)
  202. {
  203. using (SqlConnection connection = new SqlConnection(connectionString))
  204. {
  205. SqlCommand cmd = new SqlCommand(SQLString, connection);
  206. SqlParameter myParameter = new SqlParameter( "@content", SqlDbType.NText);
  207. myParameter.Value = content;
  208. cmd.Parameters.Add(myParameter);
  209. try
  210. {
  211. connection.Open();
  212. object obj = cmd.ExecuteScalar();
  213. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  214. {
  215. return null;
  216. }
  217. else
  218. {
  219. return obj;
  220. }
  221. }
  222. catch (SqlException E)
  223. {
  224. throw new Exception(E.Message);
  225. }
  226. finally
  227. {
  228. cmd.Dispose();
  229. connection.Close();
  230. }
  231. }
  232. }
  233. /// <summary>
  234. /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
  235. /// </summary>
  236. /// <param name="strSQL">SQL语句</param>
  237. /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
  238. /// <returns>影响的记录数</returns>
  239. public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
  240. {
  241. using (SqlConnection connection = new SqlConnection(connectionString))
  242. {
  243. SqlCommand cmd = new SqlCommand(strSQL, connection);
  244. SqlParameter myParameter = new SqlParameter( "@fs", SqlDbType.Image);
  245. myParameter.Value = fs;
  246. cmd.Parameters.Add(myParameter);
  247. try
  248. {
  249. connection.Open();
  250. int rows = cmd.ExecuteNonQuery();
  251. return rows;
  252. }
  253. catch (SqlException E)
  254. {
  255. throw new Exception(E.Message);
  256. }
  257. finally
  258. {
  259. cmd.Dispose();
  260. connection.Close();
  261. }
  262. }
  263. }
  264. /// <summary>
  265. /// 执行一条计算查询结果语句,返回查询结果(object)。
  266. /// </summary>
  267. /// <param name="SQLString">计算查询结果语句</param>
  268. /// <returns>查询结果(object)</returns>
  269. public static object GetSingle(string SQLString)
  270. {
  271. using (SqlConnection connection = new SqlConnection(connectionString))
  272. {
  273. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  274. {
  275. try
  276. {
  277. connection.Open();
  278. object obj = cmd.ExecuteScalar();
  279. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  280. {
  281. return null;
  282. }
  283. else
  284. {
  285. return obj;
  286. }
  287. }
  288. catch (SqlException e)
  289. {
  290. connection.Close();
  291. throw new Exception(e.Message);
  292. }
  293. }
  294. }
  295. }
  296. /// <summary>
  297. /// 执行查询语句,返回SqlDataReader(使用该方法切记要手工关闭SqlDataReader和连接)
  298. /// </summary>
  299. /// <param name="strSQL">查询语句</param>
  300. /// <returns>SqlDataReader</returns>
  301. public static SqlDataReader ExecuteReader(string strSQL)
  302. {
  303. SqlConnection connection = new SqlConnection(connectionString);
  304. SqlCommand cmd = new SqlCommand(strSQL, connection);
  305. try
  306. {
  307. connection.Open();
  308. SqlDataReader myReader = cmd.ExecuteReader();
  309. return myReader;
  310. }
  311. catch (SqlException e)
  312. {
  313. throw new Exception(e.Message);
  314. }
  315. //finally //不能在此关闭,否则,返回的对象将无法使用
  316. //{
  317. // cmd.Dispose();
  318. // connection.Close();
  319. //}
  320. }
  321. /// <summary>
  322. /// 执行查询语句,返回DataSet
  323. /// </summary>
  324. /// <param name="SQLString">查询语句</param>
  325. /// <returns>DataSet</returns>
  326. public static DataSet Query(string SQLString)
  327. {
  328. using (SqlConnection connection = new SqlConnection(connectionString))
  329. {
  330. DataSet ds = new DataSet();
  331. try
  332. {
  333. connection.Open();
  334. SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
  335. command.Fill(ds, "ds");
  336. }
  337. catch (SqlException ex)
  338. {
  339. throw new Exception(ex.Message);
  340. }
  341. return ds;
  342. }
  343. }
  344. public static DataSet Query(string SQLString, string TableName)
  345. {
  346. using (SqlConnection connection = new SqlConnection(connectionString))
  347. {
  348. DataSet ds = new DataSet();
  349. try
  350. {
  351. connection.Open();
  352. SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
  353. command.Fill(ds, TableName);
  354. }
  355. catch (SqlException ex)
  356. {
  357. throw new Exception(ex.Message);
  358. }
  359. return ds;
  360. }
  361. }
  362. /// <summary>
  363. /// 执行查询语句,返回DataSet,设置命令的执行等待时间
  364. /// </summary>
  365. /// <param name="SQLString"></param>
  366. /// <param name="Times"></param>
  367. /// <returns></returns>
  368. public static DataSet Query(string SQLString, int Times)
  369. {
  370. using (SqlConnection connection = new SqlConnection(connectionString))
  371. {
  372. DataSet ds = new DataSet();
  373. try
  374. {
  375. connection.Open();
  376. SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
  377. command.SelectCommand.CommandTimeout = Times;
  378. command.Fill(ds, "ds");
  379. }
  380. catch (SqlException ex)
  381. {
  382. throw new Exception(ex.Message);
  383. }
  384. return ds;
  385. }
  386. }
  387. #endregion
  388. #region 执行带参数的SQL语句
  389. /// <summary>
  390. /// 执行SQL语句,返回影响的记录数
  391. /// </summary>
  392. /// <param name="SQLString">SQL语句</param>
  393. /// <returns>影响的记录数</returns>
  394. public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
  395. {
  396. using (SqlConnection connection = new SqlConnection(connectionString))
  397. {
  398. using (SqlCommand cmd = new SqlCommand())
  399. {
  400. try
  401. {
  402. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  403. int rows = cmd.ExecuteNonQuery();
  404. cmd.Parameters.Clear();
  405. return rows;
  406. }
  407. catch (SqlException E)
  408. {
  409. throw new Exception(E.Message);
  410. }
  411. }
  412. }
  413. }
  414. /// <summary>
  415. /// 执行多条SQL语句,实现数据库事务。
  416. /// </summary>
  417. /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
  418. public static void ExecuteSqlTran(Hashtable SQLStringList)
  419. {
  420. using (SqlConnection conn = new SqlConnection(connectionString))
  421. {
  422. conn.Open();
  423. using (SqlTransaction trans = conn.BeginTransaction())
  424. {
  425. SqlCommand cmd = new SqlCommand();
  426. try
  427. {
  428. //循环
  429. foreach (DictionaryEntry myDE in SQLStringList)
  430. {
  431. string cmdText = myDE.Key.ToString();
  432. SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
  433. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  434. int val = cmd.ExecuteNonQuery();
  435. cmd.Parameters.Clear();
  436. trans.Commit();
  437. }
  438. }
  439. catch
  440. {
  441. trans.Rollback();
  442. throw;
  443. }
  444. }
  445. }
  446. }
  447. /// <summary>
  448. /// 执行一条计算查询结果语句,返回查询结果(object)。
  449. /// </summary>
  450. /// <param name="SQLString">计算查询结果语句</param>
  451. /// <returns>查询结果(object)</returns>
  452. public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
  453. {
  454. using (SqlConnection connection = new SqlConnection(connectionString))
  455. {
  456. using (SqlCommand cmd = new SqlCommand())
  457. {
  458. try
  459. {
  460. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  461. object obj = cmd.ExecuteScalar();
  462. cmd.Parameters.Clear();
  463. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  464. {
  465. return null;
  466. }
  467. else
  468. {
  469. return obj;
  470. }
  471. }
  472. catch (SqlException e)
  473. {
  474. throw new Exception(e.Message);
  475. }
  476. }
  477. }
  478. }
  479. /// <summary>
  480. /// 执行查询语句,返回SqlDataReader (使用该方法切记要手工关闭SqlDataReader和连接)
  481. /// </summary>
  482. /// <param name="strSQL">查询语句</param>
  483. /// <returns>SqlDataReader</returns>
  484. public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
  485. {
  486. SqlConnection connection = new SqlConnection(connectionString);
  487. SqlCommand cmd = new SqlCommand();
  488. try
  489. {
  490. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  491. SqlDataReader myReader = cmd.ExecuteReader();
  492. cmd.Parameters.Clear();
  493. return myReader;
  494. }
  495. catch (SqlException e)
  496. {
  497. throw new Exception(e.Message);
  498. }
  499. //finally //不能在此关闭,否则,返回的对象将无法使用
  500. //{
  501. // cmd.Dispose();
  502. // connection.Close();
  503. //}
  504. }
  505. /// <summary>
  506. /// 执行查询语句,返回DataSet
  507. /// </summary>
  508. /// <param name="SQLString">查询语句</param>
  509. /// <returns>DataSet</returns>
  510. public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
  511. {
  512. using (SqlConnection connection = new SqlConnection(connectionString))
  513. {
  514. SqlCommand cmd = new SqlCommand();
  515. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  516. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  517. {
  518. DataSet ds = new DataSet();
  519. try
  520. {
  521. da.Fill(ds, "ds");
  522. cmd.Parameters.Clear();
  523. }
  524. catch (SqlException ex)
  525. {
  526. throw new Exception(ex.Message);
  527. }
  528. return ds;
  529. }
  530. }
  531. }
  532. public static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  533. {
  534. if (conn.State != ConnectionState.Open)
  535. conn.Open();
  536. cmd.Connection = conn;
  537. cmd.CommandText = cmdText;
  538. if (trans != null)
  539. cmd.Transaction = trans;
  540. cmd.CommandType = CommandType.Text; //cmdType;
  541. if (cmdParms != null)
  542. {
  543. foreach (SqlParameter parameter in cmdParms)
  544. {
  545. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  546. (parameter.Value == null))
  547. {
  548. parameter.Value = DBNull.Value;
  549. }
  550. cmd.Parameters.Add(parameter);
  551. }
  552. }
  553. }
  554. #endregion
  555. #region 存储过程操作
  556. /// <summary>
  557. /// 执行存储过程 (使用该方法切记要手工关闭SqlDataReader和连接)
  558. /// </summary>
  559. /// <param name="storedProcName">存储过程名</param>
  560. /// <param name="parameters">存储过程参数</param>
  561. /// <returns>SqlDataReader</returns>
  562. public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
  563. {
  564. SqlConnection connection = new SqlConnection(connectionString);
  565. SqlDataReader returnReader;
  566. connection.Open();
  567. SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
  568. command.CommandType = CommandType.StoredProcedure;
  569. returnReader = command.ExecuteReader();
  570. //Connection.Close(); 不能在此关闭,否则,返回的对象将无法使用
  571. return returnReader;
  572. }
  573. /// <summary>
  574. /// 执行存储过程
  575. /// </summary>
  576. /// <param name="storedProcName">存储过程名</param>
  577. /// <param name="parameters">存储过程参数</param>
  578. /// <returns>结果中第一行第一列</returns>
  579. public static string RunProc(string storedProcName, IDataParameter[] parameters)
  580. {
  581. using (SqlConnection connection = new SqlConnection(connectionString))
  582. {
  583. string StrValue;
  584. connection.Open();
  585. SqlCommand cmd;
  586. cmd = BuildQueryCommand(connection, storedProcName, parameters);
  587. StrValue = cmd.ExecuteScalar().ToString();
  588. connection.Close();
  589. return StrValue;
  590. }
  591. }
  592. /// <summary>
  593. /// 执行存储过程
  594. /// </summary>
  595. /// <param name="storedProcName">存储过程名</param>
  596. /// <param name="parameters">存储过程参数</param>
  597. /// <param name="tableName">DataSet结果中的表名</param>
  598. /// <returns>DataSet</returns>
  599. public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
  600. {
  601. using (SqlConnection connection = new SqlConnection(connectionString))
  602. {
  603. DataSet dataSet = new DataSet();
  604. connection.Open();
  605. SqlDataAdapter sqlDA = new SqlDataAdapter();
  606. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  607. sqlDA.Fill(dataSet, tableName);
  608. connection.Close();
  609. return dataSet;
  610. }
  611. }
  612. public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
  613. {
  614. using (SqlConnection connection = new SqlConnection(connectionString))
  615. {
  616. DataSet dataSet = new DataSet();
  617. connection.Open();
  618. SqlDataAdapter sqlDA = new SqlDataAdapter();
  619. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  620. sqlDA.SelectCommand.CommandTimeout = Times;
  621. sqlDA.Fill(dataSet, tableName);
  622. connection.Close();
  623. return dataSet;
  624. }
  625. }
  626. /// <summary>
  627. /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
  628. /// </summary>
  629. /// <param name="connection">数据库连接</param>
  630. /// <param name="storedProcName">存储过程名</param>
  631. /// <param name="parameters">存储过程参数</param>
  632. /// <returns>SqlCommand</returns>
  633. public static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  634. {
  635. SqlCommand command = new SqlCommand(storedProcName, connection);
  636. command.CommandType = CommandType.StoredProcedure;
  637. foreach (SqlParameter parameter in parameters)
  638. {
  639. if (parameter != null)
  640. {
  641. // 检查未分配值的输出参数,将其分配以DBNull.Value.
  642. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  643. (parameter.Value == null))
  644. {
  645. parameter.Value = DBNull.Value;
  646. }
  647. command.Parameters.Add(parameter);
  648. }
  649. }
  650. return command;
  651. }
  652. /// <summary>
  653. /// 执行存储过程,返回影响的行数
  654. /// </summary>
  655. /// <param name="storedProcName">存储过程名</param>
  656. /// <param name="parameters">存储过程参数</param>
  657. /// <param name="rowsAffected">影响的行数</param>
  658. /// <returns></returns>
  659. public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
  660. {
  661. using (SqlConnection connection = new SqlConnection(connectionString))
  662. {
  663. int result;
  664. connection.Open();
  665. SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
  666. rowsAffected = command.ExecuteNonQuery();
  667. result = ( int)command.Parameters[ "ReturnValue"].Value;
  668. //Connection.Close();
  669. return result;
  670. }
  671. }
  672. /// <summary>
  673. /// 创建 SqlCommand 对象实例(用来返回一个整数值)
  674. /// </summary>
  675. /// <param name="storedProcName">存储过程名</param>
  676. /// <param name="parameters">存储过程参数</param>
  677. /// <returns>SqlCommand 对象实例</returns>
  678. public static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  679. {
  680. SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
  681. command.Parameters.Add( new SqlParameter( "ReturnValue",
  682. SqlDbType.Int, 4, ParameterDirection.ReturnValue,
  683. false, 0, 0, string.Empty, DataRowVersion.Default, null));
  684. return command;
  685. }
  686. /// <summary>
  687. /// 执行SQL语句
  688. /// </summary>
  689. /// <param name="storedProcName">存储过程名</param>
  690. /// <param name="parameters">存储过程参数</param>
  691. /// <returns>结果中第一行第一列</returns>
  692. public static string RunSql(string query)
  693. {
  694. string str;
  695. using (SqlConnection connection = new SqlConnection(connectionString))
  696. {
  697. using (SqlCommand cmd = new SqlCommand(query, connection))
  698. {
  699. try
  700. {
  701. connection.Open();
  702. //str = (cmd.ExecuteScalar().ToString() == "") ? "" : cmd.ExecuteScalar().ToString();
  703. str = "";
  704. if (cmd.ExecuteScalar() == null)
  705. {
  706. str = "";
  707. }
  708. else
  709. {
  710. str = cmd.ExecuteScalar().ToString();
  711. }
  712. return str;
  713. }
  714. catch (SqlException E)
  715. {
  716. connection.Close();
  717. throw new Exception(E.Message);
  718. }
  719. }
  720. }
  721. }
  722. #endregion
  723. }
  724. }

session工具类


  
  1. using System;
  2. using System.Web;
  3. namespace YM.Mutility
  4. {
  5. #region Session操作助手类-SessionHelper
  6. /// <summary>
  7. /// Session操作助手类
  8. /// </summary>
  9. public class SessionHelper
  10. {
  11. static SessionHelper() { HttpContext.Current.Session.Timeout = 30; }
  12. /// <summary>
  13. /// 设置一个Session
  14. /// </summary>
  15. /// <param name="key">Session的Key值</param>
  16. /// <param name="value">Session的Value值</param>
  17. public static void SetSession(string key, object value)
  18. {
  19. HttpContext.Current.Session.Remove(key);
  20. HttpContext.Current.Session.Add(key, value);
  21. }
  22. /// <summary>
  23. /// 移除Session
  24. /// </summary>
  25. /// <param name="key">Session的Key值</param>
  26. public static void RemoveSession(string key)
  27. {
  28. HttpContext.Current.Session.Remove(key);
  29. }
  30. /// <summary>
  31. /// 移除所有Session
  32. /// </summary>
  33. public static void RemoveAllSession()
  34. {
  35. HttpContext.Current.Session.RemoveAll();
  36. }
  37. /// <summary>
  38. /// 获取Session值
  39. /// </summary>
  40. /// <param name="key">Session的Key值</param>
  41. /// <returns>Session的Value值</returns>
  42. public static object GetSesstion(string key)
  43. {
  44. return HttpContext.Current.Session[key];
  45. }
  46. /// <summary>
  47. /// 获取Session(泛型)
  48. /// </summary>
  49. /// <typeparam name="T">希望获得的类型</typeparam>
  50. /// <param name="key">Session的Key值</param>
  51. /// <returns>Session的Value值</returns>
  52. public static T GetSesstion<T>(string key)
  53. {
  54. return ((T)(HttpContext.Current.Session[key]));
  55. }
  56. /// <summary>
  57. /// 设置Session超时时间
  58. /// </summary>
  59. /// <param name="timeout">超时时间(单位:分)</param>
  60. public static void SetTimeout(int timeout)
  61. {
  62. HttpContext.Current.Session.Timeout = timeout;
  63. }
  64. /// <summary>
  65. /// 获取session超时时间
  66. /// </summary>
  67. /// <returns></returns>
  68. public static int GetTimeout()
  69. {
  70. return HttpContext.Current.Session.Timeout;
  71. }
  72. }
  73. #endregion
  74. }

3.创建实体层

实体层对应数据库里的表以及列,

附上数据库创建命令


  
  1. USE [xiaobai]
  2. GO
  3. /****** Object: Table [dbo].[t_user] Script Date: 2021/3/15 22:32:52 ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. CREATE TABLE [dbo].[t_user](
  9. [ id] [ int] IDENTITY( 1, 1) NOT NULL,
  10. [username] [ varchar]( 50) NULL,
  11. [ password] [ varchar]( 50) NULL,
  12. [ name] [ varchar]( 50) NULL,
  13. [address] [ varchar]( 50) NULL,
  14. [sex] [ varchar]( 50) NULL,
  15. [mobile] [ varchar]( 50) NULL,
  16. [email] [ varchar]( 50) NULL,
  17. [qq] [ varchar]( 50) NULL,
  18. [state] [ varchar]( 50) NULL,
  19. [adddate] [ varchar]( 50) NULL,
  20. CONSTRAINT [PK_t_user] PRIMARY KEY CLUSTERED
  21. (
  22. [ id] ASC
  23. ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  24. ) ON [PRIMARY]
  25. GO

还有数据库数据截图

该例仅使用用户表进行用户登录功能,所以就写一个类


  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace YM.Model
  7. {
  8. public class User
  9. {
  10. private int id;
  11. private string username;
  12. private string password;
  13. private string name;
  14. private string address;
  15. private string sex;
  16. private string mobile;
  17. private string email;
  18. private string qq;
  19. private string state;
  20. private string adddate;
  21. public int Id { get => id; set => id = value; }
  22. public string Username { get => username; set => username = value; }
  23. public string Name { get => name; set => name = value; }
  24. public string Address { get => address; set => address = value; }
  25. public string Sex { get => sex; set => sex = value; }
  26. public string Mobile { get => mobile; set => mobile = value; }
  27. public string Email { get => email; set => email = value; }
  28. public string Qq { get => qq; set => qq = value; }
  29. public string Password { get => password; set => password = value; }
  30. public string State { get => state; set => state = value; }
  31. public string Adddate { get => adddate; set => adddate = value; }
  32. }
  33. }

4.创建数据库访问层:


  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Data;
  7. //using YM.Model;
  8. //数据库访问层
  9. namespace YM.DAL
  10. {
  11. /// <summary>
  12. /// 用户数据访问层
  13. /// </summary>
  14. public class User
  15. {
  16. /// <summary>
  17. /// 添加用户
  18. /// </summary>
  19. /// <param name="user"></param>
  20. /// <returns></returns>
  21. public static bool add(YM.Model.User user)
  22. {
  23. bool result = false;
  24. string strsql = "insert into t_user (username,password,name,address,sex,mobile,email,qq,state,adddate) values('" +
  25. user.Username + "','" + user.Password + "','" + user.Name + "','" +
  26. user.Address + "','" + user.Sex + "','" + user.Mobile + "','" +
  27. user.Email + "','" + user.Qq + "','" + user.State + "','" + user.Adddate + "');";
  28. int i = YM.Mutility.MsSqlHelper.ExecuteSql(strsql);
  29. if (i > 0)
  30. {
  31. result = true;
  32. }
  33. return result;
  34. }
  35. /// <summary>
  36. /// 判断用户是否重复
  37. /// </summary>
  38. /// <param name="username"></param>
  39. /// <returns></returns>
  40. public static bool Search(string username)
  41. {
  42. bool result = true;
  43. string strsql = "select * from t_user where username='" + username + "';";
  44. DataTable dateTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[ 0];
  45. if (dateTable.Rows.Count == 0)
  46. {
  47. result = true;
  48. }
  49. else
  50. {
  51. result = false;
  52. }
  53. return result;
  54. }
  55. /// <summary>
  56. /// 登录
  57. /// </summary>
  58. /// <param name="username"></param>
  59. /// <param name="password"></param>
  60. /// <returns></returns>
  61. public static bool Login(string username, string password)
  62. {
  63. bool result = false;
  64. string strsql = "select * from t_user where username='" + username + "' and password='" + password + "'";
  65. DataTable dateTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[ 0];
  66. if (dateTable.Rows.Count != 0)
  67. {
  68. result = true;
  69. }
  70. else
  71. {
  72. result = false;
  73. }
  74. return result;
  75. }
  76. /// <summary>
  77. /// 查找队列
  78. /// </summary>
  79. /// <returns></returns>
  80. public static List<YM.Model.User> list()
  81. {
  82. string strsql = "select * from t_user order by id desc";
  83. DataTable dataTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[ 0];
  84. return Dttolist(dataTable);
  85. }
  86. /// <summary>
  87. /// 循环赋值
  88. /// </summary>
  89. /// <param name="dt"></param>
  90. /// <returns></returns>
  91. public static List<YM.Model.User> Dttolist(DataTable dt)
  92. {
  93. List<YM.Model.User> list = new List<Model.User>();
  94. for( int i= 0;i<dt.Rows.Count; i++)
  95. {
  96. YM.Model.User user = new Model.User();
  97. user = GetUser( int.Parse(dt.Rows[i][ "id"].ToString()));
  98. list.Add(user);
  99. }
  100. return list;
  101. }
  102. /// <summary>
  103. /// 找到数据赋值给实例对象
  104. /// </summary>
  105. /// <param name="id"></param>
  106. /// <returns></returns>
  107. public static YM.Model. User GetUser(int id)
  108. {
  109. YM.Model.User user = new Model.User();
  110. string strsql = "select * from t_user where id=" + id + "";
  111. DataTable dataTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[ 0];
  112. if(dataTable.Rows.Count!= 0)
  113. {
  114. user.Id = int.Parse(dataTable.Rows[ 0][ "id"].ToString());
  115. user.Username = dataTable.Rows[ 0][ "username"].ToString();
  116. user.Password = dataTable.Rows[ 0][ "password"].ToString();
  117. user.Name = dataTable.Rows[ 0][ "Name"].ToString();
  118. user.Address = dataTable.Rows[ 0][ "Address"].ToString();
  119. user.Sex = dataTable.Rows[ 0][ "Sex"].ToString();
  120. user.Mobile = dataTable.Rows[ 0][ "Mobile"].ToString();
  121. user.Email = dataTable.Rows[ 0][ "Email"].ToString();
  122. user.Qq = dataTable.Rows[ 0][ "Qq"].ToString();
  123. user.State = dataTable.Rows[ 0][ "State"].ToString();
  124. user.Adddate = dataTable.Rows[ 0][ "Adddate"].ToString();
  125. }
  126. return user;
  127. }
  128. public static YM.Model. User GetUser1(string username)
  129. {
  130. YM.Model.User user = new Model.User();
  131. string strsql = "select * from t_user where username='" + username + "'";
  132. DataTable dataTable = YM.Mutility.MsSqlHelper.Query(strsql).Tables[ 0];
  133. if (dataTable.Rows.Count != 0)
  134. {
  135. user.Id = int.Parse(dataTable.Rows[ 0][ "id"].ToString());
  136. user.Username = dataTable.Rows[ 0][ "username"].ToString();
  137. user.Password = dataTable.Rows[ 0][ "password"].ToString();
  138. user.Name = dataTable.Rows[ 0][ "Name"].ToString();
  139. user.Address = dataTable.Rows[ 0][ "Address"].ToString();
  140. user.Sex = dataTable.Rows[ 0][ "Sex"].ToString();
  141. user.Mobile = dataTable.Rows[ 0][ "Mobile"].ToString();
  142. user.Email = dataTable.Rows[ 0][ "Email"].ToString();
  143. user.Qq = dataTable.Rows[ 0][ "Qq"].ToString();
  144. user.State = dataTable.Rows[ 0][ "State"].ToString();
  145. user.Adddate = dataTable.Rows[ 0][ "Adddate"].ToString();
  146. }
  147. return user;
  148. }
  149. public static bool del(int id)
  150. {
  151. bool result = false;
  152. string sqlstr = "delete from t_user where id=" + id + "";
  153. int i = YM.Mutility.MsSqlHelper.ExecuteSql(sqlstr);
  154. if(i> 0)
  155. {
  156. result = true;
  157. }
  158. return result;
  159. }
  160. public static bool Update(YM.Model.User user)
  161. {
  162. bool result = false;
  163. string sqlstr = "update t_user set username='" + user.Username + "',password='"+user.Password+
  164. "',address='" + user.Address + "',email='" + user.Email + "' where id=" + user.Id + ";";
  165. int i = YM.Mutility.MsSqlHelper.ExecuteSql(sqlstr);
  166. if (i > 0)
  167. {
  168. result = true;
  169. }
  170. return result;
  171. }
  172. }
  173. }

5.创建逻辑控制层


  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace YM.BLL
  7. { /// <summary>
  8. /// 用户的业务层
  9. /// </summary>
  10. public class User
  11. {
  12. /// <summary>
  13. /// 用户在业务层添加方法,调用数据库访问层
  14. /// </summary>
  15. /// <param name="user"></param>
  16. /// <returns></returns>
  17. public static bool add(YM.Model.User user)
  18. {
  19. return YM.DAL.User. add(user);
  20. }
  21. public static bool Search(string username)
  22. {
  23. return YM.DAL.User.Search(username);
  24. }
  25. public static bool Login(string username, string password)
  26. {
  27. return YM.DAL.User.Login(username, password);
  28. }
  29. public static List<YM.Model.User> list()
  30. {
  31. return YM.DAL.User.list();
  32. }
  33. public static bool del(int id)
  34. {
  35. return YM.DAL.User.del(id);
  36. }
  37. public static bool update(YM.Model.User user)
  38. {
  39. return YM.DAL.User.Update(user);
  40. }
  41. public static YM.Model. User GetUser(int id)
  42. {
  43. return YM.DAL.User.GetUser(id);
  44. }
  45. public static YM.Model. User GetUser1(string id)
  46. {
  47. return YM.DAL.User.GetUser1(id);
  48. }
  49. }
  50. }

6.编写页面,验证功能


  
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  6. <title> </title>
  7. <style type="text/css">
  8. .auto-style3 {
  9. margin-bottom: 0px;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <form id="form1" runat="server">
  15. <div>
  16. <table align="center" width="200px"> <tr> <td colspan="2">用户名: </td> <td>
  17. <asp:TextBox ID="username" runat="server"> </asp:TextBox>
  18. </td> </tr>
  19. <tr> <td colspan="2">密码: </td> <td>
  20. <asp:TextBox ID="password" runat="server"> </asp:TextBox>
  21. </td> </tr>
  22. <tr> <td>
  23. <asp:Button ID="Button1" runat="server" Text="登录" OnClick="Button1_Click" />
  24. </td>
  25. </tr>
  26. </table>
  27. </div>
  28. </form>
  29. </body>
  30. </html>

后台验证


  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. public partial class login : System.Web.UI.Page
  8. {
  9. protected void Page_Load(object sender, EventArgs e)
  10. {
  11. }
  12. protected void Button1_Click(object sender, EventArgs e)
  13. {
  14. string username = this.username.Text;
  15. string password = this.password.Text;
  16. //判断登录
  17. if(YM.BLL.User.Login(username,password)== true)
  18. {
  19. YM.Model.User user = YM.BLL.User.GetUser1(username); //获取user的值
  20. if (user.State.Equals( "1"))
  21. {
  22. YM.Mutility.SessionHelper.SetSession( "user", user);
  23. YM.Mutility.JsHelper.AlertAndRedirect( "登陆成功,", "user/index.aspx?");
  24. }
  25. }
  26. else
  27. {
  28. YM.Mutility.JsHelper.AlertAndRedirect( "登陆失败,请注册,", "reg.aspx");
  29. }
  30. }
  31. }

至此使用c#的一个用户登录功能就已经全部完成了。注意要点就是本次没有写注册功能,就需要在数据库中创建一个数据进行验证了。总结要点就是使用分层思想可以将你的整个项目的架构更清晰,后期维护容易。


转载:https://blog.csdn.net/weixin_42145499/article/details/114852421
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场