c# 中dataset的使用

来源:互联网 发布:天津广电网络营业厅 编辑:程序博客网 时间:2024/06/07 16:54

查询数据的源代码:

string conString="data source=127.0.0.1;database=test;user id=sa;password=123";string strSQL="select * from student";SqlConnection myConnection=new SqlConnection(conString);DataSet ds=new DataSet();myConnection.Open();SqlDataAdapter adapter=new SqlDataAdapter(strSQL,myConnection);adapter.Fill(ds,"ds");myconnection.Close();


封装后的代码是:

        public static DataSet Query(string StrSql)        {            using (SqlConnection connection = new SqlConnection(myConStr))            {                DataSet ds = new DataSet();                connection.Open();                SqlDataAdapter command = new SqlDataAdapter(StrSql,connection);                command.Fill(ds,"ds");                return ds;            }        }

使用的方法:
 private void button2_Click(object sender, EventArgs e)        {            string StrQuery = "select * from student";            DataSet ds = OperateDatabase.Query(StrQuery);            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)            {                string j = ds.Tables[0].Rows[i][0].ToString();                MessageBox.Show(j);            }        }