sqldataAdapter/dataset/datatable的使用

本文介绍了一个使用 C# 和 SQL 进行数据绑定的示例,包括如何从数据库加载数据到 DataGridView 控件,以及如何实现数据的增删改查功能。通过具体的代码实现了单表和多表数据绑定,并提供了手动实现增删改查的方法。

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

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //把cities表中的数据加载到窗体的datagridview
            string connString = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            using(SqlConnection sqlconn=new SqlConnection(connString))
            {
                string selectstring = @"select id, cityid, city, provinceid from cities;select * from provinces";

                 #region 单张表
                //创建一个适配器类
                //using(SqlDataAdapter sqladapter=new SqlDataAdapter(selectstring,sqlconn))
                //{

                //    //此时adapter已经连接到了一个表
                //    DataTable dataTable = new DataTable();
                //    //将关联表的数据填充到dataTable
                //    //sqladapter会自动打开数据库连接,并执行sql脚本
                //    sqladapter.Fill(dataTable);
                //    //this.dataGridView1.DataSource = dataTable;
                //    List<cities> mycitylist = new List<cities>();

                //    //类定义时字段{get;set;}不写显示不出来
                //    foreach(DataRow datarow in dataTable.Rows)
                //    {
                //        Console.WriteLine(datarow["id"]+" "+datarow[1]);
                //        //把每一行数据封装成city类 
                //            mycitylist.Add(new cities(){
                //            id=int.Parse(datarow["id"].ToString()),
                //            cityid=int.Parse(datarow["cityid"].ToString()),
                //            city=datarow["city"].ToString(),
                //            provinceid = int.Parse(datarow["provinceid"].ToString())
                //        });
                //    }
                //    //把datatable的数据转储成List<city>类型
                //    this.dataGridView1.DataSource = mycitylist;
                    #endregion

                    #region 多张表
                using(SqlDataAdapter sqlDataAdapter =new SqlDataAdapter(selectstring,sqlconn))
                {
                    DataSet dataset=new DataSet();
                    sqlDataAdapter.Fill(dataset);
                    this.dataGridView1.DataSource = dataset.Tables[0];
                }
                    #endregion

                }

            }

        }

 增删改查

 private void button1_Click(object sender, EventArgs e)
        {
            //把dataGridView修改的数据保存到数据库中
            string connString = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            string selectstring = @"select id, cityid, city, provinceid from cities;select * from provinces";
            using(SqlDataAdapter dataAdapter=new SqlDataAdapter(selectstring,connString))
            {
                //拿到修改完了之后的datatable
                DataTable dt = this.dataGridView1.DataSource as DataTable;
                //修改后dt的变化映射到数据库中对应表格的变化
                //帮助dataAdapter生成相关的CRUD 的SqlCommand
                using (SqlCommandBuilder sqlcomBulider = new SqlCommandBuilder(dataAdapter))
                {
                    dataAdapter.Update(dt);
                }
            }
            MessageBox.Show("保存成功");

手动增删改查

public static SqlDataAdapter CreateCustomerAdapter(
    SqlConnection connection)
{
    SqlDataAdapter adapter = new SqlDataAdapter();

    // Create the SelectCommand.
    SqlCommand command = new SqlCommand("SELECT * FROM Customers " +
        "WHERE Country = @Country AND City = @City", connection);

    // Add the parameters for the SelectCommand.
    command.Parameters.Add("@Country", SqlDbType.NVarChar, 15);
    command.Parameters.Add("@City", SqlDbType.NVarChar, 15);

    adapter.SelectCommand = command;

    // Create the InsertCommand.
    command = new SqlCommand(
        "INSERT INTO Customers (CustomerID, CompanyName) " +
        "VALUES (@CustomerID, @CompanyName)", connection);

    // Add the parameters for the InsertCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");

    adapter.InsertCommand = command;

    // Create the UpdateCommand.
    command = new SqlCommand(
        "UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
        "WHERE CustomerID = @oldCustomerID", connection);

    // Add the parameters for the UpdateCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
    SqlParameter parameter = command.Parameters.Add(
        "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.UpdateCommand = command;

    // Create the DeleteCommand.
    command = new SqlCommand(
        "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);

    // Add the parameters for the DeleteCommand.
    parameter = command.Parameters.Add(
        "@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.DeleteCommand = command;

    return adapter;
}

 

转载于:https://www.cnblogs.com/janghe/p/7710679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值