数据库交互(DBHelper)---转载

#region 执行增、删、改语句
            //创建连接池对象(与数据库服务器进行连接)
            SqlConnection conn = new SqlConnection("server=.;database=studentdb;uid=sa;pwd=123456");
            //创建命令对象
            SqlCommand cmd = new SqlCommand("增删改语句", conn);
            //打开连接池
            conn.Open();
            // 执行操作
            int result = cmd.ExecuteNonQuery();
            //关闭连接池
            conn.Close();
            #endregion
 
            #region 返回一个数据
            //创建连接池对象(与数据库服务器进行连接)
            SqlConnection conn = new SqlConnection("server=.;database=studentdb;uid=sa;pwd=123456");
            //创建命令对象
            SqlCommand cmd = new SqlCommand("查询语句", conn);
            //打开连接池
            conn.Open();
            // 执行命令操作
            object result = cmd.ExecuteScalar();
            //关闭连接池
            conn.Close();
            #endregion
 
            #region 返回多条数据
           
            //使用DataSet
            //创建连接池对象(与数据库服务器进行连接)
            SqlConnection conn = new SqlConnection("server=.;database=studentdb;uid=sa;pwd=123456");
            //创建命令对象
            SqlCommand cmd = new SqlCommand("查询语句", conn);
            //打开连接对象
            conn.Open(); 
            //创建数据适配器
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            //将数据适配器中的数据填充到DataSet
            da.Fill(ds);
            conn.Close();
            #endregion
posted @ 2016-03-29 17:08  时光未央岁月静好  阅读(198)  评论(0编辑  收藏  举报