将数据集插入 SQL 表中

问题描述 投票:0回答:2

我有一个数据集,其中填充了来自 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();
}

我应该怎么做才能将数据集保存在空表中?

谢谢

c# sql dataset sqldataadapter
2个回答
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 中转换它。

文献参考:

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


0
投票

在数据库中创建用户定义的表类型:

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();
© www.soinside.com 2019 - 2024. All rights reserved.