asp.net底层公共方法

简介:

DBHeper:


using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;


namespace NewsDAL

{

    

    public static  class DBHeper

    {

        

        private static SqlConnection connection;

        /// <summary>

        /// 连接数据库

        /// </summary><returns>返回 SqlConnection 对象</returns>

        public static SqlConnection Connection

        {

            get { 

                string connectionstring=ConfigurationManager.ConnectionStrings["conn"].ConnectionString.ToString();

                if(connection==null)

                {

                    connection = new SqlConnection(connectionstring);

                    connection.Open();

                }

                else if (connection.State== System.Data.ConnectionState.Closed)

                {

                    connection.Open();

                }

                else if(connection.State==System.Data.ConnectionState.Broken)

                {

                    connection.Close();

                    connection.Open();

                }

                return DBHeper.connection;

                }  

        }



        //关闭数据库连接的方法


        public static void CloesConnection() 

        {

            try { 

                if(connection.State!=ConnectionState.Closed)

                {

                 connection.Close();

                }


            }

            catch(Exception e){

                

            }

           

        }



        /// <summary>

        /// 根据 SQL语句 查询所影响的行数

        /// </summary>

        /// <param name="sql"></param>

        /// <returns>返回 int 类型</returns>

        public static int ExecutCommand(string sql) {


            try 

            {

                SqlCommand cmd = new SqlCommand(sql,Connection);

                int result = cmd.ExecuteNonQuery();

                return result;


            }catch(Exception e){

                return 0;

            }

        }




        /// <summary>

        /// 根据 SQL语句、预编译数组 查询所影响的行数

        /// </summary>

        /// <param name="sql">参数 SQL 语句</param>

        /// <param name="values">参数 预编译数组</param>

        /// <returns>返回 int 类型</returns>


        public static int ExecutCommand(string sql,params SqlParameter[] values) {

            try

            {

                SqlCommand cmd = new SqlCommand(sql,Connection);

                cmd.Parameters.Add(values);

                int result = cmd.ExecuteNonQuery();

                return result;


            }

            catch (Exception e)

            {

                return 0;

            }

        

        }


        /// <summary>

        /// 根据 SQL 语句查询得到的条数,执行查询,返回第一行第一列的值

        /// </summary>

        /// <param name="sql">参数 SQL 语句</param>

        /// <returns>返回 int 类型</returns>

        /// 

        public static int GetScalar(string sql) 

        {

            SqlCommand cmd = new SqlCommand(sql,Connection);

            int result = Convert.ToInt32(cmd.ExecuteScalar());

            return result;

        }



        /// <summary>

        /// 根据 SQL语句、预编译数组 查询得到的条数,执行查询,返回第一行第一列的值

        /// </summary>

        /// <param name="sql">参数 SQL 语句</param>

        /// <param name="values">参数 预编译数组</param>

        /// <returns>返回 int 类型</returns>

        public static int GetScalar(string sql,params SqlParameter[] values) 

        {

            SqlCommand cmd = new SqlCommand(sql,Connection);

            cmd.Parameters.AddRange(values);

            int result = Convert.ToInt32(cmd.ExecuteScalar());//cmd.ExecuteScalar()返回的是一个Ojbect类型的

            return result;

        }



        /// <summary>

        /// 根据 SQL语句 查询数据

        /// </summary>

        /// <param name="sql">参数 接受一个 SQL语句</param>

        /// <returns>返回 DataTable 类型</returns>

        /// 

        public static DataTable GetDataSet(string sql) 

        {

            DataSet ds = new DataSet();

            SqlCommand cmd = new SqlCommand(sql,Connection);

            SqlDataAdapter sda =new SqlDataAdapter(cmd);//sqlDataAdapter用于填充DataSet

            sda.Fill(ds);//向DataTable中添加数据

            return ds.Tables[0];//获得表的集合


        }



        /// <summary>

        /// 根据 SQL语句、预编译数组 查询数据

        /// </summary>

        /// <param name="sql">参数 接受一个 SQL语句</param>

        /// <param name="values">参数 接受一个 预编译数组</param>

        /// <returns>返回 DataTable 类型</returns>

        /// 


        public static DataTable GetDataSet(string sql,params SqlParameter[] values) {


            DataSet ds = new DataSet();

            SqlCommand cmd = new SqlCommand(sql,Connection);

            cmd.Parameters.AddRange(values);

            SqlDataAdapter sda = new SqlDataAdapter(cmd);

            sda.Fill(ds);

            return ds.Tables[0];

        }

    }



}




Service:


using System;

using System.Collections.Generic;

using System.Text;

using Newsentity;

using System.Data.SqlClient;

using System.Data;

using NewsDAL;




namespace NewsDAL

{

   public class newsService

    {

        #region

        /// <summary>

        /// 得到所有信息

        /// </summary>

        /// <returns></returns>

        /// 

        #endregion

        public static List<news> GetNews()

        {

            string sql = "SELECT * FROM NEWS";

            DataTable tables = DBHeper.GetDataSet(sql);

            List<news > list = new List<news>();

            if (tables.Rows.Count > 0)

            {

                for (int i = 0; i < tables.Rows.Count; i++)

                {

                    news n = new news();

                    n.Nid = Convert.ToInt32(tables.Rows[i]["nid"]);

                    n.Sname = Convert.ToString(tables.Rows[i]["sname"]);

                    n.Spass =Convert.ToString(tables.Rows[i]["spass"]); 

                    n.Stype=Convert.ToString(tables.Rows[i]["stype"]);

                    n.Ncontent = Convert.ToString(tables.Rows[i]["ncontent"]);

                    list.Add(n);

                }

                return list;

            }

            else

            {

                return null;

            }

        }




       //根据类型查询新闻

        public static List<news> GetByNews(string type)

        {

            string sql=string.Format("SELECT * FROM NEWS WHERE STYPE='{0}'",type);

            DataTable tables = DBHeper.GetDataSet(sql);

            List<news> list = new List<news>();

            if (tables.Rows.Count > 0)

            {

                for (int i = 0; i < tables.Rows.Count; i++)

                {

                    news n = new news();

                    n.Sname = Convert.ToString(tables.Rows[i]["sname"]);

                    n.Spass = Convert.ToString(tables.Rows[i]["spass"]);

                    n.Stype = Convert.ToString(tables.Rows[i]["stype"]);

                    n.Ncontent = Convert.ToString(tables.Rows[i]["ncontent"]);

                    list.Add(n);

                }

                return list;

            }

            else

            {

                return null;

            }

        }




        //验证用户登陆

        public static news GetNewstLogin(string name, string pass)

        {

            string sql = string.Format("SELECT * FROM NEWS WHERE SNAME='{0}' and SPASS='{1}'", name, pass);

            DataTable tables = DBHeper.GetDataSet(sql);

            if (tables.Rows.Count != 0)

            {

                news n = new news();

                n.Sname = Convert.ToString(tables.Rows[0]["sname"]);

                n.Spass = Convert.ToString(tables.Rows[0]["spass"]);

                n.Stype = Convert.ToString(tables.Rows[0]["stype"]);

                n.Ncontent = Convert.ToString(tables.Rows[0]["ncontent"]);

                return n;

            }

            else

            {

                return null;

            }


        }



        //删除记录

        public static int DelectNews(int id)

        {

            string sql = string.Format("DELETE FROM NEWS WHERE NID in ('{0}')", id);

            int result = DBHeper.ExecutCommand(sql);

            return result;

        }


        //删除记录

        public static int DelectNews(string  id)

        {

            string sql = string.Format("DELETE FROM NEWS WHERE NID in ({0})", id);

            int result = DBHeper.ExecutCommand(sql);

            return result;

        }


        //根据id查询详细信息

        public static List<news> GetNewsById(int id)

        {

            string sql = string.Format("SELECT * FROM NEWS WHERE NID={0}", id);

            DataTable tables = DBHeper.GetDataSet(sql);

            List<news > list = new List<news>();

            if (tables.Rows.Count != 0)

            {

                news n = new news();

                n.Sname = Convert.ToString(tables.Rows[0]["sname"]);

                n.Spass = Convert.ToString(tables.Rows[0]["spass"]);

                n.Stype = Convert.ToString(tables.Rows[0]["stype"]);

                n.Ncontent = Convert.ToString(tables.Rows[0]["ncontent"]);

                list.Add(n);

                return list;

            }

            else

            {

                return null;

            }

        }



        //添加信息

        public static int AddNews(news n)

        {

            string sql = string.Format("insert into news(ncontent,spass,sname,stype) values('{0}','{1}','{2}','{3}')",n.Ncontent,n.Spass,n.Sname,n.Stype);

            int result = DBHeper.ExecutCommand(sql);

            if (result > 0)

            {

                return result;

            }

            else

            {

                return 0;

            }

        }



        //修改信息

        public static int UpdateNews(news n)

        {

            string sql = string.Format("UPDATE NEWS SET NCONTENT='{0}',SNAME='{1}',SPASS='{2}',STYPE='{3}' WHERE NID='{4}'",n.Ncontent,n.Sname,n.Spass,n.Stype,n.Nid);

            int result = DBHeper.ExecutCommand(sql);

            if (result > 0)

            {

                return result;

            }

            else

            {

                return 0;

            }

        }


    }

}





配置文件


<?xml version="1.0"?>

<!-- 

    注意: 除了手动编辑此文件以外,您还可以使用 

    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的

     “网站”->“Asp.Net 配置”选项。

    设置和注释的完整列表在 

    machine.config.comments 中,该文件通常位于 

    \Windows\Microsoft.Net\Framework\v2.x\Config 中

-->

<configuration>

<appSettings/>

<connectionStrings>

<add name="conn" connectionString="uid=sa;pwd=123456;server=.\sqlexpress;database=NEWS"/>

</connectionStrings>

<system.web>

    <httpModules>

      <add type="Discuz.Forum.HttpModule, Discuz.Forum" name="HttpModule" />

    </httpModules>

<!-- 

            设置 compilation debug="true" 可将调试符号插入

            已编译的页面中。但由于这会 

            影响性能,因此只在开发过程中将此值 

            设置为 true。

        -->

<compilation debug="true" targetFramework="4.0">

</compilation>

<!--

            通过 <authentication> 节可以配置 ASP.NET 用来 

            识别进入用户的

            安全身份验证模式。 

        -->

<authentication mode="Windows"/>

<!--

            如果在执行请求的过程中出现未处理的错误,

            则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,

            开发人员通过该节可以配置

            要显示的 html 错误页

            以代替错误堆栈跟踪。


        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">

            <error statusCode="403" redirect="NoAccess.htm" />

            <error statusCode="404" redirect="FileNotFound.htm" />

        </customErrors>

        -->

<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>

</configuration>

本文转自程序猿博客51CTO不可靠,原文链接http://blog.51cto.com/haihuiwei/1622232如需转载请自行联系原作者


365850153

相关文章
|
开发框架 前端开发 安全
ASP.NET Core Startup类Config gure()方法|ASP.NET Core 中间件详细说明
目录 Startup 类 Configure() 方法 中间件 使用中间件 Configure 方法 的参数 IApplicationBuilder Extension Methods(拓展方法)--微软提供的中间件
146 0
ASP.NET Core Startup类Config gure()方法|ASP.NET Core 中间件详细说明
|
SQL 存储 XML
ASP.NET Core 实战:基于 Dapper 扩展你的数据访问方法
ASP.NET Core 实战:基于 Dapper 扩展你的数据访问方法 一、前言 在非静态页面的项目开发中,必定会涉及到对于数据库的访问,最开始呢,我们使用 Ado.Net,通过编写 SQL 帮助类帮我们实现对于数据库的快速访问,后来,ORM(Object Relational Mapping,对象关系映射)出现了,我们开始使用 EF、Dapper、NHibernate,亦或是国人的 SqlSugar 代替我们原来的 SqlHelper.cs。
4135 0
|
Web App开发 监控 .NET
ASP.NET Web API 记录请求响应数据到日志的一个方法
原文:ASP.NET Web API 记录请求响应数据到日志的一个方法 原文:http://blog.bossma.cn/dotnet/asp-net-web-api-log-request-response/ ASP.NET Web API 记录请求响应数据到日志的一个方法 REST风格的服务架构已经成为越来越多人的选择,之前我用过WCF来实现REST服务,WCF是一个很强大的框架,干这点小事有点太沉重的感觉。
1467 0
|
SQL 安全 .NET
ASP.net防止SQL注入方法
1、sql注入比较难防,需要替换select,delete等一打字符  其实对于字符型替换再多都没有替换单引号为两个单引号来的好!对于数字型替换再多都没有用,一定要类型转换。
1456 0
|
前端开发 .NET 开发框架
asp.net core中遇到需要自定义数据包解密方法的时候
最近将公司的项目用.netcore重写, 服务的http外部接口部分收发消息是DES加解密的, 那么在asp.net core mvc的action处理之前需要加入解密这个步骤.  我第一想到的是用filter的方法来做, 找到了ActionFilter, 重写了OnActionExecuting方法, 确实成功在action执行前拦截了下来, 但是request却是只读的.
1130 0
|
.NET 开发框架 JavaScript
asp.net mvc5 下载文件方法
控制器自带的 FileContentResult 可以让我们很方便的返回文件到服务端,减少了很多步骤。用于下载文件的时候,像视频、文本、图片这种浏览器支持的文件,默认就会被浏览器打开。这时候想让它变成下载,还需要设置一下响应头,告诉浏览器如何处理才行。
989 0
|
.NET C# 数据安全/隐私保护
|
.NET 网络架构 数据安全/隐私保护