首页 > 编程 > C# > 正文

C#的SQL操作类实例

2020-01-24 02:22:24
字体:
来源:转载
供稿:网友

本文实例讲述了C#的SQL操作类,分享给大家供大家参考。具体方法如下:

复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace yjgl
{
    /// <summary>   
    /// 数据访问基础类(SQL)   
    /// </summary>
    class BaseOperate
    {
        #region  建立数据库连接
        /// <summary>
        /// 建立数据库连接.
        /// </summary>
        /// <returns>返回SqlConnection对象</returns>
        public SqlConnection getcon()
        {
            string M_str_sqlcon = "Data Source=PC-200201010009 ;Database=db_yjzl;User ID=sa;PWD=123";//连接字符串
            SqlConnection mycon = new SqlConnection(M_str_sqlcon);      //创建连接对象
            return mycon;
        }
        #endregion
        #region  执行SqlCommand命令
        /// <summary>
        /// 执行SqlCommand
        /// </summary>
        /// <param name="M_str_sqlstr">SQL语句</param>
        public void getcom(string M_str_sqlstr)
        {
            SqlConnection sqlcon = this.getcon();   //获取连接字符串
            sqlcon.Open();       //打开连接
            try
            {
                SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon);  //通过SQL语句和连接对象创建命令对象
                sqlcom.ExecuteNonQuery();     //对sqlcon执行SQL语句并返回受影响的行数
                sqlcom.Dispose();           //释放sqlcom'
            }
            catch (SqlException e)
            {
                MessageBox.Show(e.ToString(), "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                sqlcon.Close();
                sqlcon.Dispose();
            }
        }
        #endregion
        #region  创建DataSet对象
        /// <summary>
        /// 创建一个DataSet对象
        /// </summary>
        /// <param name="M_str_sqlstr">SQL语句</param>
        /// <param name="M_str_table">表名</param>
        /// <returns>返回DataSet对象</returns>
        public DataSet getds(string M_str_sqlstr, string M_str_table)  //查询
        {
            SqlConnection sqlcon = this.getcon();
            SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlda.Fill(myds, M_str_table);
            return myds;
         }
        #endregion
         #region  创建SqlDataReader对象
         /// <summary>
         /// 创建一个SqlDataReader对象
         /// </summary>
         /// <param name="M_str_sqlstr">SQL语句</param>
         /// <returns>返回SqlDataReader对象</returns>
        public SqlDataReader getread(string M_str_sqlstr)
        {
            SqlConnection sqlcon = this.getcon();
            SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon);
            sqlcon.Open();
            SqlDataReader sqlread = sqlcom.ExecuteReader(CommandBehavior.CloseConnection);
            return sqlread;
           
         }
        #endregion
    }
}

希望本文所述对大家的C#程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表