Datagridview实现自动更新到数据库

时间:2021-12-07 09:04:36

针对Access数据库介绍使用方法

DataTable tb;
OleDbDataAdapter da;
private void bindData()
{
    string dateStr = DateTime.Now.ToShortDateString();
    tb = db.QueryTable("select [account].[id] ,[pid],[account].[username],[account].[password],[account].[otherdata],iif(isnull(success),'-',success)  as state from account left join [record] on ([aid]=[account].[id]  and [record].[getDate]='" + dateStr + "') where ( [pid]=" + IDIndex.ToString() + ")");
    OleDbConnection con = new OleDbConnection(db.connectionString);
    da = new OleDbDataAdapter("select * from account ", con);
    OleDbCommandBuilder scb = new OleDbCommandBuilder(da);//可自动生成更新,插入,删除sql语句
    scb.QuotePrefix = "[";
    scb.QuoteSuffix = "]";
            
    dataGridView1.DataSource = tb;
}

主要是通过OleDbCommandBuilder来实现的,这里需要注意的是不需要手动给OleDbCommandBuilder设置删、改的语句,但是如果查询语句很复杂是无法正确生成删、改的语句的,所以要手动设置一个最简单的查询语句,很简单吧,几行代码就搞定一切。