在数据库中插入数据集记录 [英] Insert dataset records in database

查看:66
本文介绍了在数据库中插入数据集记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据集记录(C#)插入MS Accessdatabase表中.我需要批量插入记录.

I need to insert the dataset records(C#) into the MS Accessdatabase table. I need to do the bulk insertion of records.

如何在C#中做到这一点

How can I do this in C#

推荐答案

对于此类任务,请考虑使用数据适配器抽象.对于Microsoft Access数据库,可以使用 <代码> OleDbDataAdapter 实现,如下例所示:

For this sort of task, consider using the data adapter abstraction. With an Microsoft Access database, you can use the OleDbDataAdapter implementation as shown in the example below:

// Prerequisite: The data to be inserted is available in a DataTable/DataSet.
var data = new DataTable();
data.Columns.Add("CompanyName", typeof(string));
data.Columns.Add("Phone", typeof(string));
data.Rows.Add("Foo", "12345678");
data.Rows.Add("Bar", "87654321");

// Now, open a database connection using the Microsoft.Jet.OLEDB provider.
// The "using" statement ensures that the connection is closed no matter what.
using (var connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=Northwind.mdb"))
{
    connection.Open();

    // Create an OleDbDataAdapter and provide it with an INSERT command.
    var adapter = new OleDbDataAdapter();
    adapter.InsertCommand = new OleDbCommand("INSERT INTO Shippers (CompanyName, Phone) VALUES (@CompanyName , @Phone)", connection);
    adapter.InsertCommand.Parameters.Add("CompanyName", OleDbType.VarChar, 40, "CompanyName");
    adapter.InsertCommand.Parameters.Add("Phone", OleDbType.VarChar, 24, "Phone");

    // Hit the big red button!
    adapter.Update(data);
}

您也可以针对其他品牌的数据库引擎执行相同的操作,方法是将 OleDbCommand OleDbDataAdapter OleDbConnection 替换为适合您的实现数据库引擎.对于Microsoft SQL Server,请查找带有 Sql 前缀的类,例如. SqlCommand

You can do the same against other brands of database engines as well by replacing OleDbCommand, OleDbDataAdapter and OleDbConnection with the appropriate implementations for your database engine. For Microsoft SQL Server, look for classes prefixed with Sql, eg. SqlCommand.

这篇关于在数据库中插入数据集记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆