将数据从Data表导出到Access数据库c#

时间:2017-08-15 17:55:18

标签: c# ms-access

我有一个数据表,我想更新访问数据库表。所以,我编写了如下代码。

DataTable table = new DataTable();
// table has some data...
OleDbConnection db_conn1 = new 
OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + source);
db_conn1.Open();
OleDbCommand cmd = new OleDbCommand(); 
OleDbCommand cmd1 = new OleDbCommand();
cmd.Connection = db_conn1;
cmd.CommandType = CommandType.Text;
cmd1.Connection = db_conn1;
cmd1.CommandType = CommandType.Text;
for (int i = 0; i <= (table.Rows.Count - 1); i++)
{
     cmd.CommandText = "INSERT INTO access_table(Id, " + table.Columns[0].ColumnName.Trim() + ") VALUES (" + (i + 1) + ",'" + table.Rows[i].ItemArray.GetValue(0) + "')";
     cmd.ExecuteNonQuery();
     for (int j = 1; j <= (table.Columns.Count - 1); j++)
     {
          cmd1.CommandText = "UPDATE [access_table] SET [" + table.Columns[j].ColumnName.Trim() + "] = @add WHERE [Id] = @add1";
          cmd1.Parameters.AddWithValue("@add",table.Rows[i].ItemArray.GetValue(j));
          cmd1.Parameters.AddWithValue("@add1", (i+1));
          cmd1.ExecuteNonQuery();
     }
}

但我得到这样的输出:

Id        Name
 1         A
 2
 3
 .
 .
 N

但在第二栏中,我只获得了一次性的价值。我在哪里弄错了?

2 个答案:

答案 0 :(得分:0)

您不断向命令对象添加参数,因此请尝试清除它们:

for (int j = 1; j <= (table.Columns.Count - 1); j++)
{
  cmd1.CommandText = "UPDATE [access_table] SET [" + table.Columns[j].ColumnName.Trim() + "] = @add WHERE [Id] = @add1";
  cmd1.Parameters.Clear();
  cmd1.Parameters.AddWithValue("@add",table.Rows[i].ItemArray.GetValue(j));
  cmd1.Parameters.AddWithValue("@add1", (i+1));
  cmd1.ExecuteNonQuery();
}

答案 1 :(得分:0)

通过将所有字段添加到INSERT语句,INSERT然后不更新会更有效。你可以这样做:

using (var db_conn1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + source))
{
    db_conn1.Open();
    using (var cmd = new OleDbCommand())
    {
        cmd.Connection = db_conn1;
        cmd.CommandType = CommandType.Text;
        string firstSQL = "INSERT INTO access_table(Id";
        for (int i = 0; i <= (table.Rows.Count - 1); i++)
        {
            cmd.Parameters.Clear();
            string midSQL = ") VALUES(" + (i + 1).ToString();

            StringBuilder colNames = new StringBuilder();
            StringBuilder valParams = new StringBuilder();
            for (int j = 1; j <= (table.Columns.Count - 1); j++)
            {
                colNames.Append(", " + table.Columns[j].ColumnName.Trim());
                string paramName = "@add" + j.ToString();
                valParams.Append(", " + paramName);
                cmd.Parameters.AddWithValue(paramName, table.Rows[i].ItemArray.GetValue(j));
            }
            cmd.CommandText = firstSQL + colNames.ToString() + midSQL + valParams.ToString() + ")";
            cmd.ExecuteNonQuery();
        }
    }
}

请注意,我在使用部分时也包含了OleDbConnection和OleDbCommand。这是推荐的做法,因为它们都实现了IDisposable。这样做意味着垃圾收集器(“GC”)知道它可以在使用后安全地处理对象 - 并且数据连接使用大量资源,因此最好尽快清理。