C#获取数据库的数据

来源:互联网 发布:python教学 编辑:程序博客网 时间:2024/05/16 06:39
                string str = "server=NO1;database=SuperMarket;integrated security=true";                SqlConnection con = new SqlConnection(str);                con.Open();                SqlDataAdapter ad = new SqlDataAdapter("select * from food where foodid='" + bh + "'", con);                DataSet set = new DataSet();                ad.Fill(set, "n1");                int kucun = Convert.ToInt32(set.Tables["n1"].Rows[0]["foodnum"]);                int mon = Convert.ToInt32(set.Tables["n1"].Rows[0]["foodvalue"]);


               string str = "server=NO1;database=SuperMarket;integrated security=true";
                SqlConnection con = new SqlConnection(str);
                con.Open();

               表示与数据库建立连接(用户名为NO1,数据库名称SuperMarket),并打开
               SqlDataAdapter ad = new SqlDataAdapter("select * from food where foodid='" + bh + "'", con);

                获取选中的行
               DataSet set = new DataSet();
                ad.Fill(set, "n1");

                将行放入set容器中,n1为当前数据集的名字

                因为foodid为主键,所以只有一行元素。如果有多行,用个循环就好
               int kucun = Convert.ToInt32(set.Tables["n1"].Rows[0]["foodnum"]);
                int mon = Convert.ToInt32(set.Tables["n1"].Rows[0]["foodvalue"]);

               set.Tables["n1"].Rows[0]["foodnum"]) 表示set的n1表中的第0行“foodid”列的数据取出来

原创粉丝点击