当前位置: 代码迷 >> C# >> 几个强大的工具类,不看您得后悔咯
  详细解决方案

几个强大的工具类,不看您得后悔咯

热度:372   发布时间:2016-04-28 08:20:32.0
几个强大的工具类,不看你得后悔咯

 

SqlHelper类

作用:充当一个助人为乐的角色。这个类呢,任何类都可以调用。例如:数据的“增, 删, 改 ,查”,数据库的链接,等等。

这个类是静态类,只要用类名.方法名(),就可以使用该方法的功能了。

//与数据交互的方法    public static class SQLHelper    {        //创建静态方法,方便调用        //配置文件        public static string str = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;       // public static string str = "data source=.;initial catalog=myschool;uid=sa;pwd=123";        //执行NonQuery命令       public static int ExecuteNonQuery(string cmdTxt, params SqlParameter[] parames)        {            return ExecuteNonQuery(cmdTxt, CommandType.Text, parames);        }        //可以使用存储过程的ExecuteNonQuery        public static int ExecuteNonQuery(string cmdTxt, CommandType commandType, params SqlParameter[] parames)        {            //判断脚本是否为空,直接返回0            if (string.IsNullOrEmpty(cmdTxt))            {                return 0;            }            using (SqlConnection con = new SqlConnection(str))            {                using (SqlCommand cmd = new SqlCommand(cmdTxt, con))                {                    if (parames != null)                    {                        cmd.CommandText = cmdTxt;                        cmd.Parameters.AddRange(parames);                    }                    con.Open();                    return cmd.ExecuteNonQuery();                }            }        }        public static SqlDataReader ExecuteDataReader(string cmdTxt, params SqlParameter[] parames)        {            return ExecuteDataReader(cmdTxt, CommandType.Text, parames);        }        //SQLDataReader存储过程方法        public static SqlDataReader ExecuteDataReader(string cmdTxt, CommandType commandType, params SqlParameter[] parames)        {            if (string.IsNullOrEmpty(cmdTxt))            {                return null;            }            SqlConnection con = new SqlConnection(str);            using (SqlCommand cmd = new SqlCommand(cmdTxt, con))            {                cmd.CommandType = commandType;                if (parames != null)                {                    cmd.Parameters.AddRange(parames);                }                con.Open();                //把reader的行为加进来。当reader释放资源的时候,con也被一块关闭                return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);            }        }        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parames)        {            return ExecuteDataTable(sql, CommandType.Text, parames);        }        //调用存储过程的类,关于(ExecuteDataTable)        public static DataTable ExecuteDataTable(string sql, CommandType commandType, SqlParameter[] parames)        {            if (string.IsNullOrEmpty(sql))            {                return null;            }            DataTable dt = new DataTable();            using (SqlDataAdapter da = new SqlDataAdapter(sql, str))            {                da.SelectCommand.CommandType = commandType;                if (parames != null)                {                    da.SelectCommand.Parameters.AddRange(parames);                }                da.Fill(dt);                return dt;            }        }        /// <summary>        /// ExecuteScalar        /// </summary>        /// <param name="cmdTxt">第一个参数,SQLServer语句</param>        /// <param name="parames">第二个参数,传递0个或者多个参数</param>        /// <returns></returns>        ///         public static object ExecuteScalar(string cmdTxt, params SqlParameter[] parames)        {            return ExecuteScalar(cmdTxt, CommandType.Text, parames);        }        //可使用存储过程的ExecuteScalar        public static object ExecuteScalar(string cmdTxt, CommandType commandType, SqlParameter[] parames)        {            if (string.IsNullOrEmpty(cmdTxt))            {                return null;            }            using (SqlConnection con = new SqlConnection(str))            {                using (SqlCommand cmd = new SqlCommand(cmdTxt, con))                {                    cmd.CommandType = commandType;                    if (parames != null)                    {                        cmd.Parameters.AddRange(parames);                    }                    con.Open();                    return cmd.ExecuteScalar();                }            }        }        //调用存储过程的DBHelper类(关于ExeceutScalar,包含事务,只能处理Int类型,返回错误号)        public static object ExecuteScalar(string cmdTxt, CommandType commandType, SqlTransaction sqltran, SqlParameter[] parames)        {            if (string.IsNullOrEmpty(cmdTxt))            {                return 0;            }            using (SqlConnection con = new SqlConnection(str))            {                int sum = 0;                using (SqlCommand cmd = new SqlCommand(cmdTxt, con))                {                    cmd.CommandType = commandType;                    if (parames != null)                    {                        cmd.Parameters.AddRange(parames);                    }                    con.Open();                    sqltran = con.BeginTransaction();                    try                    {                        cmd.Transaction = sqltran;                        sum = Convert.ToInt32(cmd.ExecuteScalar());                        sqltran.Commit();                    }                    catch (SqlException ex)                    {                        sqltran.Rollback();                    }                    return sum;                }            }        }          }}
MyTool类

作用:简化代码,提高性能,提高运行效率。

string sql = "select * from grade";
DataTable dt = SQLHelper.ExecuteDataTable(sql);

MyTool tool=new MyTool();
List<Grade> list=tool.DataTableToList<Grade>(dt);

相当于foreach循环

上面四行代码相当于下面十行代码

List<Grade> list = new List<Grade>();
string sql = "select * from grade";
DataTable dt = SQLHelper.ExecuteDataTable(sql);

//将dt转成List<Student>
foreach (DataRow row in dt.Rows)
{
 //每一个row代表表中的一行 所以 一行对应一个年级对象

 Grade grade = new Grade();
 grade.GradeId = Convert.ToInt32(row["gradeid"]);
 grade.GradeName = row["gradename"].ToString();
 list.Add(grade);
}

public class MyTool    {        /// <summary>        /// DataSetToList        /// </summary>        /// <typeparam name="T">转换类型</typeparam>        /// <param name="dataSet">数据源</param>        /// <param name="tableIndex">需要转换表的索引</param>        /// <returns></returns>        public List<T> DataTableToList<T>(DataTable dt)        {            //确认参数有效            if (dt == null )                return null;            List<T> list = new List<T>();            for (int i = 0; i < dt.Rows.Count; i++)            {                //创建泛型对象                T _t = Activator.CreateInstance<T>();                //获取对象所有属性                PropertyInfo[] propertyInfo = _t.GetType().GetProperties();                for (int j = 0; j < dt.Columns.Count; j++)                {                    foreach (PropertyInfo info in propertyInfo)                    {                        //属性名称和列名相同时赋值                        if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))                        {                            if (dt.Rows[i][j] != DBNull.Value)                            {                                info.SetValue(_t, dt.Rows[i][j], null);                            }                            else                            {                                info.SetValue(_t, null, null);                            }                            break;                        }                    }                }                list.Add(_t);            }            return list;        }    }}

MsgDiv类

作用:该类相当于一个控件。我们知道有这么TextBox控件,及文本框。

但是有时候我们需要美化文字,所以就要用MsgDiv控件。而且该控件还有一个特别的作用:计时器,

就是有时间的延长,即当你运行一个窗体时,你不想马上就要看到

该窗体,所以呢,可以用该控件设置时间 的延续,已达到效果。

首先你把这个类放项目窗体下面。

效果图:

/// <summary>/// 消息条回调函数委托/// </summary>public delegate void DGMsgDiv();    /// <summary>    /// 消息条类 带Timer计时    /// </summary>public class MsgDiv : System.Windows.Forms.Label{    private Timer timerLable = new Timer();    /// <summary>    /// 消息回调 委托对象    /// </summary>    private DGMsgDiv dgCallBack = null;    #region 计时器    /// <summary>    /// 计时器    /// </summary>    public Timer TimerMsg    {        get { return timerLable; }        set { timerLable = value; }    }     #endregion    #region  MsgDiv构造函数    /// <summary>    /// MsgDiv构造函数    /// </summary>    public MsgDiv()    {        InitallMsgDiv(7, 7);    }    /// <summary>    /// MsgDiv构造函数    /// </summary>    /// <param name="x">定位x轴坐标</param>    /// <param name="y">定位y轴坐标</param>    public MsgDiv(int x, int y)    {        InitallMsgDiv(x, y);    }    #endregion    #region  初始化消息条    /// <summary>    /// 初始化消息条    /// </summary>    private void InitallMsgDiv(int x, int y)    {        this.AutoSize = true;        this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));        this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;        //this.ContextMenuStrip = this.cmsList;        this.Font = new System.Drawing.Font("宋体", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));        this.ForeColor = System.Drawing.Color.Red;        this.Location = new System.Drawing.Point(x, y);        this.MaximumSize = new System.Drawing.Size(980, 525);        this.Name = "msgDIV";        this.Padding = new System.Windows.Forms.Padding(7);        this.Size = new System.Drawing.Size(71, 31);        this.TabIndex = 1;        this.Text = "消息条";        this.Visible = false;        //给委托添加事件        this.DoubleClick += new System.EventHandler(this.msgDIV_DoubleClick);        this.MouseLeave += new System.EventHandler(this.msgDIV_MouseLeave);        this.MouseHover += new System.EventHandler(this.msgDIV_MouseHover);        this.timerLable.Interval = 1000;        this.timerLable.Tick += new System.EventHandler(this.timerLable_Tick);    }    #endregion    #region 将消息条添加到指定容器上    /// <summary>    /// 将消息条添加到指定容器上Form    /// </summary>    /// <param name="form"></param>    public void AddToControl(Form form)    {        form.Controls.Add(this);    }    /// <summary>    /// 将消息条添加到指定容器上GroupBox    /// </summary>    /// <param name="form"></param>    public void AddToControl(GroupBox groupBox)    {        groupBox.Controls.Add(this);    }    /// <summary>    /// 将消息条添加到指定容器上Panel    /// </summary>    /// <param name="form"></param>    public void AddToControl(Panel panel)    {        panel.Controls.Add(this);    }    #endregion    //---------------------------------------------------------------------------    #region 消息显示 的相关参数们 hiddenClick,countNumber,constCountNumber    /// <summary>    /// 当前显示了多久的秒钟数    /// </summary>    int hiddenClick = 0;    /// <summary>    /// 要显示多久的秒钟数 可变参数    /// </summary>    int countNumber = 3;    /// <summary>    /// 要显示多久的秒钟数 固定参数    /// </summary>    int constCountNumber = 3;     #endregion    #region 计时器 显示countNumber秒钟后自动隐藏div -timerLable_Tick(object sender, EventArgs e)    private void timerLable_Tick(object sender, EventArgs e)    {        if (hiddenClick > countNumber - 2)        {            MsgDivHidden();        }        else        {            hiddenClick++;            //RemainCount();        }    }     #endregion    #region 隐藏消息框 并停止计时 +void MsgDivHidden()    /// <summary>    /// 隐藏消息框 并停止计时    /// </summary>    public void MsgDivHidden()    {        this.Text = "";        this.Visible = false;        this.hiddenClick = 0;        //this.tslblRemainSecond.Text = "";        if (this.timerLable.Enabled == true)            this.timerLable.Stop();        //调用 委托 然后清空委托        if (dgCallBack != null && dgCallBack.GetInvocationList().Length > 0)        {            dgCallBack();            dgCallBack -= dgCallBack;        }    }     #endregion    #region 在消息框中显示消息字符串 +void MsgDivShow(string msg)    /// <summary>    /// 在消息框中显示消息字符串    /// </summary>    /// <param name="msg">要显示的字符串</param>    public void MsgDivShow(string msg)    {        this.Text = msg;        this.Visible = true;        this.countNumber = constCountNumber;//默认设置显示秒数为10;        this.hiddenClick = 0;//重置倒数描述        this.timerLable.Start();    }     #endregion    #region 在消息框中显示消息字符串 并在消息消失时 调用回调函数 +void MsgDivShow(string msg, DGMsgDiv callback)    /// <summary>    /// 在消息框中显示消息字符串 并在消息消失时 调用回调函数    /// </summary>    /// <param name="msg">要显示的字符串</param>    /// <param name="callback">回调函数</param>    public void MsgDivShow(string msg, DGMsgDiv callback)    {        MsgDivShow(msg);        dgCallBack = callback;    }    #endregion    #region 在消息框中显示消息字符串 并在指定时间消息消失时 调用回调函数 +void MsgDivShow(string msg, int seconds, DGMsgDiv callback)    /// <summary>    /// 在消息框中显示消息字符串 并在消息消失时 调用回调函数    /// </summary>    /// <param name="msg">要显示的字符串</param>    /// <param name="seconds">消息显示时间</param>    /// <param name="callback">回调函数</param>    public void MsgDivShow(string msg, int seconds, DGMsgDiv callback)    {        MsgDivShow(msg, seconds);        dgCallBack = callback;    }      #endregion    #region 在消息框中显示消息字符串,并指定消息框显示秒数 +void MsgDivShow(string msg, int seconds)    /// <summary>    /// 在消息框中显示消息字符串,并指定消息框显示秒数    /// </summary>    /// <param name="msg">要显示的字符串</param>    /// <param name="seconds">消息框显示秒数</param>    public void MsgDivShow(string msg, int seconds)    {        this.Text = msg;        this.Visible = true;        this.countNumber = seconds;        this.hiddenClick = 0;//重置倒数描述        this.timerLable.Start();    }     #endregion    //---------------------------------------------------------------------------    #region 事件们~~~! msgDIV_MouseHover,msgDIV_MouseLeave,msgDIV_DoubleClick    //当鼠标停留在div上时 停止计时    private void msgDIV_MouseHover(object sender, EventArgs e)    {        if (this.timerLable.Enabled == true)            this.timerLable.Stop();    }    //当鼠标从div上移开时 继续及时    private void msgDIV_MouseLeave(object sender, EventArgs e)    {        //当消息框正在显示、回复框没显示、计时器正停止的时候,重新启动计时器        if (this.Visible == true && this.timerLable.Enabled == false)            this.timerLable.Start();    }    //双击消息框时关闭消息框    private void msgDIV_DoubleClick(object sender, EventArgs e)    {        MsgDivHidden();    }     #endregion}

上面这三个类的代码,虽然是老师给的代码,但是都是经过本人认真写出来的,目的就是强化记忆。望对大家有帮助。

谢谢!

2楼hbxiaoqiao
这些都是最少五年前的东西了,有ef等,有linq等这些好久没用了。 (来自博客园v3.3.2)
1楼NOGiveUp
  相关解决方案