2007/05/15 | 对常见对数据中的操作的总结
类别(MsMvp) | 评论(5) | 阅读(53) | 发表于 10:48

对数据库库进行常见的操作包括对数据库进行最基本的修改,删除,查询等,我将以代码的形式对其表示:

 //创建连接
public static SqlConnection Createconn()
        {
            return new SqlConnection("server=.;database=test;uid=sa;pwd=;");//可以修改
        }
        //返回DataSet
        public static DataSet Readds(string strsql)
        {
            SqlConnection conn = Createconn();
            SqlCommand cmd = new SqlCommand(strsql,conn);
            SqlDataAdapter sda = new SqlDataAdapter();
            DataSet ds = new DataSet();
            sda.SelectCommand = cmd;
            sda.Fill(ds,"tablename");
            return ds;
        }
        //返回DataTable
        public static DataTable Readtb(string strsql)
        {
            SqlConnection conn = Createconn();
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataAdapter sda = new SqlDataAdapter();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            sda.SelectCommand = cmd;
            sda.Fill(ds, "tablename");
            dt=ds.Tables["tablename"];
            return dt;
        }
        //返回一行数据
        public static SqlDataReader Dr(string strsql)
        {
            SqlConnection conn = Createconn();
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataReader sdr = cmd.ExecuteReader();
            if (sdr.Read())
            {
                return sdr;
            }
            else
            {
                return null;
            }
        }
        //返回表中的一个字段
        public string Readstring(string strsql, int flag)
        {
            string restr;
            SqlConnection conn = Createconn();
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataAdapter sda = new SqlDataAdapter();
            DataSet ds = new DataSet();
            sda.SelectCommand = cmd;
            sda.Fill(ds, "tablename");
            restr = ds.Tables["tablename"].Rows[0].ItemArray[flag].ToString();
            return restr;
        }
        //对数据库执行非查询语句
        public void executesql(string strsql)
        {
            SqlConnection conn = Createconn();
            SqlCommand cmd = new SqlCommand(strsql, conn);
            cmd.ExecuteNonQuery();
 
        }

0

评论Comments

日志分类
首页[25]
我的日志[11]
MsMvp[8]
我的故事[5]
生活小记[1]