我一直在阅读MSDN资源和几个论坛,但仍然不明白这两个dataAdapter.Fill()dataAdapter.Update()有什么区别,我试图同时使用这两个更新程序来更新数据库,并且可以正常工作,但是当我尝试删除update()函数,它仍然可以正常工作,因此我认为它没有用。

任何人都可以澄清一下吗?

编辑:
这是我要删除的代码:

string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Public\\Documents\\inventorySystem\\branches\\Database\\inventorySystemDatabase.accdb";
string query = "DELETE FROM Product WHERE product_id=" + productDataGridView[1, e.RowIndex].Value.ToString();
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
OleDbCommandBuilder deleteBuilder = new OleDbCommandBuilder(dAdapter);
DataTable deleteTable = new DataTable();
dAdapter.Update(deleteTable);

-我必须执行一个额外的select命令来更新datagridview-

最佳答案

工作样本

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private OleDbConnection con =
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\test.mdb\";");

        private OleDbDataAdapter adapter;
        DataTable table = new DataTable("person");

        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            con.Open();
            ;
            adapter = new OleDbDataAdapter("select ID, p_name, p_age from person", con);
            adapter.Fill(table);
            OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
            adapter.DeleteCommand = builder.GetDeleteCommand();
            adapter.UpdateCommand = builder.GetUpdateCommand();
            adapter.InsertCommand = builder.GetInsertCommand();
            dataGridView1.DataSource = table;

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            con.Close();
            con.Dispose();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DataRow[] row = table.Select("p_age = 10");
            if (row.Length > 0)
            {
                for (int i = 0; i < row.Length; i++)
                {
                    row[i].Delete();
                }
            }
            adapter.Update(table);
        }

    }
}

简单来说。

DataAdapter.Fill()用于从数据库加载数据

示例:显示从数据库到gridview的数据
using (DataTable table = new DataTable()) {

    using (OleDbDataAdapter adapter = new OleDbDataAdapter("select name,age from person", conObject)) {

        adapter.Fill(table);
        BindingSource bs = new BindingSource { DataSource = table };
        dgReader.DataSource = bs;
    }

}

完成编辑后,DataAdapter.Update()使用基础连接将所有更改的数据信息提交到数据库。

DataAdapter.Fill()



DataAdapter.Update()

关于c# - dataAdapter .Fill和.Update的比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14305447/

10-11 04:34