C SqlDataAdapter,读取数据库数据

博客提到SqlDataAdapter具有自动管理数据库连接的功能,能自动打开和关闭数据库连接,即自动执行conn.open()和conn.close()操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

               

SqlDataAdapter  会自动打开数据库连接,关闭连接。(自动 conn.open()  conn.close())

using System;using System.Collections.Generic;using System.ComponentModel;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace _01SqlDataAdapterDemo{    public partial class MainFrm : Form    {        public MainFrm()        {            InitializeComponent();        }        private void MainFrm_Load(object sender, EventArgs e)        {            //把UserInfo表中数据加载到 窗体的DataGridView            string connStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;            using (SqlConnection conn = new SqlConnection(connStr))            {                string strSql = "select UserId, UserName, UserAge, DelFlag, CreateDate, UserPwd, LastErrorDateTime, ErrorTimes from userinfo ";                //创建一个 适配器类。                using (SqlDataAdapter adapter = new SqlDataAdapter(strSql,conn))                {                    DataTable dt =new DataTable();                                         //把数据库中的数据填充到内存表Dt中。                    //填充之前不需要打开数据库连接,Adapter会自动打开连接,并执行sql。                    adapter.Fill(dt);                    //dt.Rows[0][1]  //第一行第一列的值                    List<UserInfo> userList =new List<UserInfo>();                    foreach (DataRow dataRow in dt.Rows)                    {                          Console.WriteLine(dataRow["UserId"] + "   " + dataRow[1]);  //dataRow[1]  第一列的值                        //把每一行数据封装成 UesrInfo对象。                        userList.Add(new UserInfo()                        {                            Id=int.Parse(dataRow["UserId"].ToString()),                            UserName = dataRow["UserName"].ToString(),                            UserAge =int.Parse(dataRow["UserAge"].ToString())                        });                    }                    //把dt的数据转换成List<UserInfo>                     this.dgvUserInfo.DataSource = userList;  //DataGridView控件                }            }        }    }}


           
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值