将dataSet插入SQL表

时间:2013-11-19 07:12:32

标签: c# sql dataset sqldataadapter

我有一个数据集,其中包含来自3个不同表格的数据。我想将该数据集存储在SQL中的空表中,我已经创建了表。

public void SaveDataBaseTailleALL(DataGridView dataGridViewRALSelectedTaille, DataSet oDSALL)
{
    PointageCls.totalPointage(dataGridViewRALSelectedTaille);
    SqlConnection cn = new SqlConnection();
    cn.ConnectionString = "Data Source=HOOSSEN-HP\\INFO2;Initial Catalog=SuiviOF;User ID=sa;Password= PROTECTED;"
    //string strSQL = ")";

    SqlDataAdapter adapt = new SqlDataAdapter("select * from tblTailleALL)", cn);
    SqlCommandBuilder builder = new SqlCommandBuilder(adapt);
    adapt.update(oDSALL.Tables[0]);
    oDSALL.Tables[0].AcceptChanges();
}

如何在空表中保存数据集?

感谢

2 个答案:

答案 0 :(得分:0)

可参考以下代码:

public static OleDbDataAdapter CreateCustomerAdapter(
    OleDbConnection connection)
{
    OleDbDataAdapter adapter = new OleDbDataAdapter();
    OleDbCommand command;

    // Create the SelectCommand.
    command = new OleDbCommand("SELECT CustomerID FROM Customers " +
        "WHERE Country = ? AND City = ?", connection);

    command.Parameters.Add("Country", OleDbType.VarChar, 15);
    command.Parameters.Add("City", OleDbType.VarChar, 15);

    adapter.SelectCommand = command;

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

    command.Parameters.Add(
        "CustomerID", OleDbType.Char, 5, "CustomerID");
    command.Parameters.Add(
        "CompanyName", OleDbType.VarChar, 40, "CompanyName");

    adapter.InsertCommand = command;
    return adapter;
}

它的OLEDB,但语法上你可以用sql转换它。

Doccumental Referance:

http://msdn.microsoft.com/en-us/library/system.data.common.dbdataadapter.insertcommand(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

答案 1 :(得分:0)

在数据库中创建用户定义的TableType:

CREATE TYPE [dbo].[TableType] AS TABLE(
[UserId] int NOT NULL,
[UserName] [nvarchar](128) NULL,
[Password] [varchar](30)

并在您的存储过程中定义一个参数:

CREATE PROCEDURE [dbo].[InsertTable]
@myTableType TableType readonly
AS
BEGIN
insert into [dbo].Users select * from @myTableType 
END

并将您的DataTable直接发送到sql server:

 SqlCommand command = new SqlCommand("InsertTable");
 command.CommandType = CommandType.StoredProcedure;
 var dt = new DataTable(); //create your own data table
 command.Parameters.Add(new SqlParameter("@myTableType", dt));
 command.ExecuteNonQuery();