C#中SqlDataAdapter 适配器 获取数据库中的数据
程序员文章站
2024-01-25 09:11:16
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;usi......
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 DataSetDome
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGetData_Click(object sender, EventArgs e)
{
String connStr = ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;
using (SqlConnection connSql = new SqlConnection(connStr))//建立连接对象
{
string strSql = "select UserID,UserName,UserPwd from UserInfo";
//创建一个适配器类
//方式二:SqlDataAdapter adapter1 = new SqlDataAdapter(strSql, connStr);
using (SqlDataAdapter adapter = new SqlDataAdapter(strSql,connSql))
{
//DataSet dt = new DataSet();
DataTable dt = new DataTable();//填充DataTable
//填充之前,不需要打开数据库连接,Adapter会自动打开连接,并执行sql
//Fill方法内部:
//1、先判断SqlConnection 是否初始化 ,如果没有就先打开连接
//2、初始化一个Select SqlCommand对象
//3、通过cmd对象执行一下,返回SqlDataReader对象
//4、读取数据库中的数据,填充到内存表中去
adapter.Fill(dt);//读取数据库中的数据 填充到内存表中
adapter.Fill(new DataSet(), "s");//DataSet一次可以读取多张表的数据
List<UseInfo> userList = new List<UseInfo>();
foreach (DataRow item in dt.Rows)
{
userList.Add(new UseInfo() { UserId = item["UserID"].ToString(), UserName = item["UserName"].ToString(), UserPwd = item["UserPwd"].ToString()});
}
this.dataGridView1.DataSource = userList;
}
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;
string strSql = "select UserID,UserName,UserPwd from UserInfo2";
//创建一个适配器类
//方式二:SqlDataAdapter adapter1 = new SqlDataAdapter(strSql, connStr);
using (SqlDataAdapter adapter1 = new SqlDataAdapter(strSql, connStr))
{
// List<UseInfo> dt_list = this.dataGridView1.DataSource as List<UseInfo>;
DataTable dt = this.dataGridView1.DataSource as DataTable;
// UserID,UserName,UserPwd
//DataColumn dcId = new DataColumn("UserID", typeof(string));
//DataColumn dcName = new DataColumn("UserName", typeof(string));
//DataColumn dcPwd = new DataColumn("UserPwd", typeof(string));
//dt.Columns.AddRange(new DataColumn[] { dcId, dcName, dcPwd });
//foreach (UseInfo item in dt_list)
//{
// dt.Rows.Add(item.UserId, item.UserName, item.UserPwd);
//}
//SqlCommandBuilder 帮助我们的Adapter生成相关的CRUD SqlCommand
using (SqlCommandBuilder scb = new SqlCommandBuilder(adapter1))
{
adapter1.Update(dt);
}
}
}
本文地址:https://blog.csdn.net/qq_42885712/article/details/85962020