-1

我有DataTable并且我需要添加row默认值并将其保存到数据库中。

奖励:自动递增键列会很棒。

我怎样才能做到这一点?

4

2 回答 2

0
static int i = 1;
private void CreateDefault()
{
    DataColumn column = null;
    DataTable table = new DataTable();

    column = new DataColumn();
    var Col1 = column;
    Col1.DataType = System.Type.GetType("System.Int32");
    Col1.DefaultValue = i;
    Col1.Unique = false;
    table.Columns.Add(column);
    i = i + 1;

    column = new DataColumn();
    var Col2 = column;
    Col2.DataType = System.Type.GetType("System.String");
    Col2.DefaultValue = "Your String";
    table.Columns.Add(column);

    DataRow row = null;
    row = table.NewRow();

    table.Rows.Add(row);
}

变量i将是自动递增键列。现在插入DataTableDataBase

于 2015-10-10T05:52:06.247 回答
-1

您可以使用默认值添加新行并将其保存到数据库中,如下所示。

using (var conn = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand("SELECT * FROM YourTableName", conn);
    SqlDataAdapter da = new SqlDataAdapter() { SelectCommand = cmd };

    // Load records to a DataSet
    DataSet ds = new DataSet();
    da.Fill(ds, "YourTableName");
    var table = ds.Tables["YourTableName"];

    // Add a new row with default value
    table.Rows.Add();

    // Reflect the change to database
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    da.Update(ds, "YourTableName");
}

此外,如果您为 MS SQL Server ( https://msdn.microsoft.com/en-us/library/ms186775.aspx ) 设置了自动增量键(如 IDENTITY),则在插入新行时可以使用。

于 2015-10-10T06:12:12.387 回答