调用数据库的类

来源:互联网 发布:我知主掌握明天歌谱 编辑:程序博客网 时间:2024/06/05 08:03
    class DbMyself
    {//应用于连接调用数据库的类


        private string sqlcon = "Data Source=192.168.132.205;Initial Catalog=TTry;Integrated Security=false;User ID = sa; Password=123;Max Pool Size=512;";
        //连接数据库的字符串
        private SqlConnection con = new SqlConnection();
        public DbMyself()//构造函数,用于创建对象的同时打开数据库
        {
             con = new SqlConnection(sqlcon);//SqlConnection 表示 SQL Server 数据库的一个打开的连接。
            con.Open();//打开数据库
        }
        public int RunSQL_GetNum(string sql)//执行sql语句,并返回受影响行数
        {
            SqlCommand cmd = new SqlCommand();
            using (cmd = con.CreateCommand()) //在相应的数据库下创建命令
                //using的作用是在using中的语句执行结束或发生异常时退出using
            {
                cmd.CommandText = sql;//将需要执行的sql语句交付给命令
                cmd.CommandType = CommandType.Text;//CommandType是SqlCommand对象的一个属性,
                                                   //用于指定执行动作的形式,它告诉.net接下来执行的是一个文本(text)、存储过程(StoredProcedure)还是表名称(TableDirect).
                                                   //此处为Text
                int n = cmd.ExecuteNonQuery();//执行sql语句,并将受影响行数赋给n
                return n;
            }
        }
        public DataTable RunSql_GetTable(string sql)//执行sql语句,并返回一张表
        {
            SqlCommand cmd = new SqlCommand();
            using (cmd = con.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter(cmd);//sql数据接收
                DataSet ds = new DataSet();
                sda.Fill(ds,"table");//将sql中的数据充斥到ds中
                DataTable dt = ds.Tables[0];
                return dt;
            }
        }
        public DataTable RunProc_GetTable(string proc, params SqlParameter[] list)//执行存储过程,并返回一张表
            //在这里说明一点,存储过程如果没有参数,调用函数时不用要后面的参数
        {
            SqlCommand cmd = new SqlCommand();
            using (cmd = con.CreateCommand())
            {
                cmd.CommandText = proc;
                cmd.CommandType = CommandType.StoredProcedure;//命令文本的类型是存储过程
                cmd.Parameters.AddRange(list);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                sda.Fill(ds,"table");
                DataTable dt = ds.Tables[0];
                return dt;
            }
        }
        public int RunProc_GetNum(string proc, params SqlParameter[] list)//执行存储过程,并返回受影响行数
        {
            SqlCommand cmd = new SqlCommand();
            using (cmd = con.CreateCommand())
            {
                cmd.CommandText = proc;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddRange(list);
                int n = cmd.ExecuteNonQuery();
                return n;
            }
        }


    }
原创粉丝点击