Asp.net DB类

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Web;
using System.Collections;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Data.SqlClient;

namespace DBTool
{
    public class DB
    {

        public static OleDbConnection conn = null;
        public static string GetConnStringOut()
        {
            string s = System.Configuration.ConfigurationManager.ConnectionStrings["smconn"].ConnectionString.ToString();
            return s;
        }
        public static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        public string GetConnString()
        {
            string s = System.Configuration.ConfigurationManager.ConnectionStrings["smconn"].ConnectionString.ToString();
            return s;
        }
        /// <summary>
        /// 打开数据库连接
        /// </summary>
        public void OpenConn()
        {
            try
            {
                //if (conn == null)
                //{
                    conn = new OleDbConnection();
                    conn.ConnectionString = this.GetConnString();
               // }
                //if (conn != null && conn.State == ConnectionState.Closed)
                    conn.Open();
            }
            catch
            {
            }
        }
        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void CloseConn()
        {
            if (conn != null && conn.State == ConnectionState.Open)
                conn.Close();
            conn.Dispose();
        }
        /// <summary>
        /// 执行查询返回DataTable
        /// </summary>
        /// <param name="sql">要执行查询的sql语句</param>
        /// <returns>DataTable</returns>
        public DataTable RunSqlGetDataTable(string sql)
        {

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(sql, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds.Tables[0];
            }
        }
        /// <summary>
        /// 执行非查询返回影响行数
        /// </summary>
        /// <param name="sql">要执行非查询的sql语句</param>
        /// <returns> int </returns>
        public int RunSqlGetRowCount(string sql)
        {
            OpenConn();
            OleDbCommand cmd = new OleDbCommand(sql, conn);
            int rowcount = -1;
            try
            {
                rowcount = cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                string sTmp = ex.Message.ToLower();
                if (sTmp.IndexOf("重复键") >= 0)
                {
                    //MessageBox.Show("不允许重复!");
                }
                else if (sTmp.IndexOf("reference") >= 0)
                {
                    //MessageBox.Show("数据已经被使用!");
                }
                else
                {
                    rowcount = -3;//主要是为了在系统重建的时候使用
                }
            }
            catch { }

            CloseConn();
            return rowcount;
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string
        /// using the provided parameters.
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch (Exception ex)
            {
                conn.Close();
                throw new Exception(ex.Message);
            }
        }
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, 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 = cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        /// <summary>
        /// 执行非查询返回影响行数
        /// </summary>
        /// <param name="sql">要执行非查询的sql语句  返回id</param>
        /// <returns> int </returns>
        public int RunSqlGetRowCountReturnId(string sql)
        {
            OpenConn();
            OleDbCommand cmd = new OleDbCommand(sql, conn);
            object rowcount = "0";
            try
            {
                rowcount = cmd.ExecuteScalar();
            }
            catch (OleDbException ex)
            {
                string sTmp = ex.Message.ToLower();
                if (sTmp.IndexOf("重复键") >= 0)
                {  //MessageBox.Show("不允许重复!");
                }
                else if (sTmp.IndexOf("reference") >= 0)
                { //MessageBox.Show("数据已经被使用!");
                }
                else
                {
                    rowcount = -3;//主要是为了在系统重建的时候使用
                }
            }
            catch { }
            CloseConn();
            return int.Parse(rowcount.ToString());
        }

        /// <summary>
        /// 返回查询结果集中第一行第一列
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns>object</returns>
        ///
        public object RunSqlGetObject(string sql)
        {
            OpenConn();
            OleDbCommand cmd = new OleDbCommand(sql, conn);

            object o = cmd.ExecuteScalar();
            CloseConn();
            return o;
        }

        ///
        /// <summary>
        /// 获得一个具有事务功能的数据库连接对象
        /// </summary>
        /// <param name="tconn"></param>
        /// <param name="transaction"></param>
        public void OpenTransConn(ref OleDbConnection tconn, ref OleDbTransaction transaction)
        {

            try
            {
                if (tconn == null)
                {
                    tconn = new OleDbConnection();
                    tconn.ConnectionString = this.GetConnString();
                }
                if (tconn != null && tconn.State == ConnectionState.Closed)
                {
                    tconn.Open();
                    transaction = tconn.BeginTransaction();
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// 关闭事务数据库连接
        /// </summary>
        public void CloseTransConn(ref OleDbConnection tconn, ref OleDbTransaction transaction)
        {
            if (transaction != null)
            {
                transaction.Commit();//提交事务
            }
            if (tconn != null && tconn.State == ConnectionState.Open)
                tconn.Close();
        }

        public bool RunTransSqlGetBool(ref OleDbConnection tconn, ref OleDbTransaction transaction, string sql)
        {
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = tconn;
            cmd.CommandText = sql;
            cmd.Transaction = transaction;
            int rowcount = -1;
            try
            {
                rowcount = cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                if (ex.ErrorCode == -2147217873)
                {
                    //MessageBox.Show("不能添加重复的值!");
                }
                else
                {
                    //MessageBox.Show("不能添加重复的值!");
                }
                transaction.Rollback();
                return false;
            }
            catch { }
            if (rowcount > 0)
                return true;
            return false;
        }
        //通过事务完成增加一系列记录
        public bool RunTransSqls(ArrayList sqlAl)
        {
            int rowcount = -1;

            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = this.GetConnString();
            OleDbTransaction tran = null;
            OleDbCommand cmd = null;

            #region MyRegion
            try
            {
                conn.Open();
                tran = conn.BeginTransaction();
                cmd = new OleDbCommand();
                cmd.Connection = conn;
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;

                foreach (string sql in sqlAl)
                {
                    //MessageBox.Show(sql);
                    rowcount = -1;
                    cmd.CommandText = sql;
                    rowcount = cmd.ExecuteNonQuery();

                    if (rowcount <= 0)//有些时候是没有数据的,也算成功
                    {
                        //tran.Rollback();
                        //return false;
                    }
                }
                tran.Commit();
                return true;
            }
            catch (Exception ex)
            {
                tran.Rollback();
                //MessageBox.Show(ex.Message);
            }
            finally
            {
                try
                {
                    if (conn != null && conn.State == ConnectionState.Open)
                        conn.Close();
                    if (conn != null)
                        conn.Dispose();
                }
                catch { }
            }
            #endregion

            return false;
        }

        //通过存储过程  添加删除和修改
        public int RunProcGetReturnValue(string procName, ArrayList al)
        {
            int re = 0;
            //数据库连接
            OpenConn();
            try
            {
                //定义命令对象
                #region
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = conn;//关联数据库连接对象
                cmd.CommandText = procName;//设置存储过程名称
                cmd.CommandType = CommandType.StoredProcedure;//命令类型
                #endregion
                cmd.Parameters.Clear();
                //设置返回参数return ,
                //注意:返回参数必须写在参数列表的第一个位置
                OleDbParameter paramReturn = new OleDbParameter("returnvalue", OleDbType.VarChar, 50);
                paramReturn.Direction = ParameterDirection.ReturnValue;//参数传递方向;默认传入
                paramReturn.Value = -1;//返回值
                cmd.Parameters.Add(paramReturn);//增加返回参数到命令对象cmd
                foreach (OleDbParameter p in al)
                {
                    cmd.Parameters.Add(p);
                }
                cmd.ExecuteNonQuery();

                re = Convert.ToInt32(paramReturn.Value);
            }
            catch { }
            finally
            {
                CloseConn();
            }
            return re;
        }

        public int RunProcGetOutputValue(string procName, ArrayList al)
        {
            //数据库连接
            OpenConn();
            //定义命令对象
            #region
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;//关联数据库连接对象
            cmd.CommandText = procName;//设置存储过程名称
            cmd.CommandType = CommandType.StoredProcedure;//命令类型
            #endregion
            cmd.Parameters.Clear();
            foreach (OleDbParameter p in al)
            {
                cmd.Parameters.Add(p);
            }
            try
            {
                return cmd.ExecuteNonQuery(); ;
            }
            catch
            {
                return 0;
            }
            finally
            {
                CloseConn();
            }
        }
        //通过存储过程 查询(不带参数的查询)
        public DataSet RunProcGetDataTable(string procName)
        {
            //数据库连接
            OpenConn();
            //定义命令对象
            #region
            ArrayList al = new ArrayList();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;//关联数据库连接对象
            cmd.CommandText = procName;//设置存储过程名称
            cmd.CommandType = CommandType.StoredProcedure;//命令类型
            #endregion
            cmd.Parameters.Clear();

            foreach (OleDbParameter p in al)
            {
                cmd.Parameters.Add(p);
            }
            try
            {
                DataSet ds = new DataSet();
                OleDbDataAdapter da = new OleDbDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);
                return ds;
            }
            catch
            {
                return null;
            }
            finally
            {
                CloseConn();
            }
        }

        // 通过存储过程查询数据(带参数的)
        public DataTable RunSqlGetDataTableFY(string name, int id)
        {
            OpenConn();
            OleDbDataAdapter da = null;
            DataTable dt = null;
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;
            cmd.CommandText = name; ;
            cmd.CommandType = CommandType.StoredProcedure;

            OleDbParameter p2 = new OleDbParameter("@Id", OleDbType.Integer, 4);
            p2.Value = id;
            cmd.Parameters.Add(p2);
            try
            {
                da = new OleDbDataAdapter();
                da.SelectCommand = cmd;
                dt = new DataTable();
                da.Fill(dt);
            }
            catch { }
            CloseConn();
            return dt;
        }
        public static OleDbConnection Getconn()
        {
            try
            {

                if (conn != null && conn.State == ConnectionState.Closed)
                    conn.Open();
            }
            catch
            {
            }
            return conn;
        }
        /// <summary>
        /// 导出报表文件为csv格式
        /// </summary>
        public static bool DataDownTOcsv(string sql, string filename, string tableheader1, string tableheader2, string columname, int columcount)
        {
            try
            {
                string strFileToOrg = "", strBufferLine = "", strBufferLine1 = "";
                int i;
                strFileToOrg = HttpContext.Current.Server.MapPath("~/pdf/" + filename + ".csv");
                StreamWriter strmWriterObj = new StreamWriter(strFileToOrg, false, System.Text.Encoding.Default);//声明写入流对象
                //OleDbConnection OleDbConnection1=new OleDbConnection();
                OleDbConnection OleDbConnection1 = DB.Getconn();
                //OleDbConnection1.ConnectionString="File Name="+HttpContext.Current.Server.MapPath("conn.udl");
                //OleDbConnection1.Open();
                OleDbCommand cmdGenFile = new OleDbCommand();
                cmdGenFile.Connection = OleDbConnection1;
                cmdGenFile.CommandText = sql;
                OleDbDataReader drGenFile = cmdGenFile.ExecuteReader();
                strmWriterObj.WriteLine(tableheader1);
                strmWriterObj.WriteLine(tableheader2);
                strmWriterObj.WriteLine(columname);
                while (drGenFile.Read())
                {
                    strBufferLine = "";
                    strBufferLine1 = Convert.ToString(drGenFile.GetValue(0));
                    strBufferLine = strBufferLine1;
                    for (i = 1; i <= (columcount - 1); i++)
                    {
                        strBufferLine1 = "";
                        strBufferLine1 = Convert.ToString(drGenFile.GetValue(i));
                        strBufferLine = strBufferLine + "," + strBufferLine1;
                    }
                    strmWriterObj.WriteLine(strBufferLine);
                }
                strmWriterObj.Close();
                drGenFile.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public bool MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case "HW"://指定高宽缩放(可能变形)
                    break;
                case "W"://指定宽,高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减(不变形)
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                return true;
            }
            catch (System.Exception e)
            {
                throw e;
                return false;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

    }
}

  

时间: 2024-10-05 09:49:40

Asp.net DB类的相关文章

非常不错的ASP操作数据库类,支持多数据库MSSQL,ACCESS,ORACLE,MYSQL等

可同时操作多个不同类型的数据库. 完全不用考虑数据类型的差别,再也不用想字符型字段加不加单引号. 调用非常简单,对数据库的主要操作一般只需要一行代码. 支持mssql事务回滚. 可自动生成和输出sql语句方便调试. 使用方法: 1. 修改clsDbctrl.asp文件中的第1行为你自己的数据库位置(修改方法参考下面的CreatConn函数说明).如需连接多个数据库可自行添加,格式相同. 2. 在你新建的asp文件中包含此asp文件.如: <!--#include file="Inc/cls

封装自己的DB类(PHP)

封装一个DB类,用来专门操作数据库,以后凡是对数据库的操作,都由DB类的对象来实现.这样有了自己的DB类,写项目时简单的sql语句就不用每次写了,直接调用就行,很方便! 1.封装一个DB类.一个类文件应该只有一个类,其他的内容全部都没有.类文件的命名规则:类名.class.php 下面是创建DB类的代码: <?php //封装一个DB类,用来专门操作数据库,以后凡是对数据库的操作,都由DB类的对象来实现 class DB{ //属性 private $host; private $port; p

ASP经典分页类

================================================================= 'XDOWNPAGE ASP版本 '版本 1.00 'Code by zykj2000 'Email: [email protected] 'BBS: http://bbs.513soft.net '本程序可以免费使用.修改,希望我的程序能为您的工作带来方便 '但请保留以上请息 ' '程序特点 '本程序主要是对数据分页的部分进行了封装,而数据显示部份完全由用户自定义

ASP.Net string 类的扩展方法 [转]

string 类的扩展方法列表(基本相同于 IEnumerable<T> 接口的成员列表): Aggregate<>     //累加 All<>        //是否都满足条件 Any<>        //是否有一个满足条件 AsEnumerable<>  // AsParallel<>    // AsQueryable<>    // Average<>      //平均值 Cast<>

nodejs操作mongodb数据库封装DB类

这个DB类也算是我经历了3个实际项目应用的,现分享出来,有需要的请借鉴批评. 上面的注释都挺详细的,我使用到了nodejs的插件mongoose,用mongoose操作mongodb其实蛮方便的. 关于mongoose的安装就是 npm install -g mongoose 这个DB类的数据库配置是基于auth认证的,如果您的数据库没有账号与密码则留空即可. /** * mongoose操作类(封装mongodb) */ var fs = require('fs'); var path = r

php自己封装一个Db类,跟tp5封装的类一模一样

上代码: <?php //自己创建一个数据库Db类 class Db { private $db_host;//主机名 private $db_user;//主机账号 private $db_password;//主机密码 private $db_name;//选择数据库 private $db_char;//选择字符集 private $link;//创建链接对象 public function __construct($db_host2,$db_user2,$db_password2,$db

Android DB类,支持MDB,SQLITE,SQLSERVER,支持查询、事务,对象直接插入和更新操作等

直做数据库,最近花了点时间把自己常用的东西封装在一起. DBHelper using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using System.Reflection; namespace DBHelper { public sealed class DB : IDisposable { #region 数据库类型枚举

封装类似thinkphp连贯操作数据库的Db类(简单版)。

<?php header("Content-Type:text/html;charset=utf-8"); /** *php操作mysql的工具类 */ class Db{ private $_db = null;//数据库连接句柄 private $_table = null;//表名 private $_where = null;//where条件 private $_order = null;//order排序 private $_limit = null;//limit限

DB类

database class-DB.class.php 1 <?php 2 3 //工具类:专门负责操作数据库(mysql) 4 5 class DB{ 6 //定义属性 7 private $host; //主机地址 8 private $port; //端口 9 private $user; //用户名 10 private $pass; //密码 11 private $dbname;//数据库名字 12 private $charset; //字符集 13 14 private $lin