爱吃酸菜鱼的猫

c#简单的数据库查询与绑定DataGridView。

1配置文件 (两种写法)

<connectionStrings>
    <add name="connStr" connectionString="server=.;database=数据库名;Uid=sa;Pwd=密码"/>
  </connectionStrings>
  <appSettings>
    <add key="conStr" value="server=.;database=数据库名;Uid=sa;Pwd=密码”/>
  </appSettings>

2读取配置中的信息(两种写法)

 string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ToString();

  string connStr1 = System.Configuration.ConfigurationManager.AppSettings["connStr"];

3.连接数据库,执行数据库操作,返回ds

  private string Sql()//拼接数据库语句
        {
            string sql = "select * from test order by Id asc";
            return sql;
        }

private void btnGetData_Click(object sender, EventArgs e)
        {
            string sql = Sql();
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            SqlCommand comm = new SqlCommand(sql, conn);
            SqlDataAdapter dap = new SqlDataAdapter(comm);
            DataSet ds = new DataSet();
            dap.Fill(ds, "test");
            conn.Close();
            conn.Dispose();

            success(ds);

        }

4.绑定DataGridView

        /// <summary>
        /// 把数据表转变为List
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private List<Data> TableToList(DataTable dt)
        {
            List<Data> objList = new List<Data>();
            int rowsCounts = dt.Rows.Count;
            if (rowsCounts > 0)
            {
                Data model;
                for (int i = 0; i < rowsCounts; i++)
                {
                    model = new Data();
                    model.ID = int.Parse(dt.Rows[i]["ID"].ToString());
                    if (dt.Rows[i]["Value"].ToString() != "")
                    {
                        model.Value = dt.Rows[i]["Value"].ToString();
                    }
                    objList.Add(model);
                }
            }
            return objList;
        }

       /// <summary>
        /// 绑定数据,并展示在DataGridView
        /// </summary>
        /// <param name="ds"></param>
        private void success(DataSet ds)
        {
            DataTable dt = ds.Tables[0];
            List<Data> objList = TableToList(dt);
            foreach (var item in objList)
            {
                if (objList.Count > 0)
                {
                    dataGridView1.Rows.Add(item.ID, "", item.Value);
                }
            }
        }

5执行结果图

 

posted on 2018-04-16 11:50  爱吃酸菜鱼的猫  阅读(681)  评论(0编辑  收藏  举报

导航