将一个数据库表的数据复制到另一个数据库表

问题描述 投票:1回答:1

我正在尝试编写一个C#应用程序,它将OleDb数据库的一个表中的数据读取到另一个OleDb数据库表中。源和目标表将在运行时由用户决定。

我现在正在做的方法是,将所有内容读入OleDbDataReader,遍历每一行并插入到其他表中。

  // create insert string
  insert = "INSERT INTO " + Dest_Table + " VALUES (";
  for(int i = 0; i < cols.Length; i++)       // cols is array of column names
  {
      string coma = ", ";
      if (i == cols.Length - 1)
      coma = " )";

      insert += "?" + coma;
  }

  // read each row and insert
  while (src_reader.Read())
  {
      dstcmd.CommandText = insert;

      for (int i = 0; i < cols.Length; i++)
      {
          string temp = "@" + cols[i];
          dstcmd.Parameters.AddWithValue(temp, src_reader[cols[i]]);

          // for debug purpose
          Console.Write(temp + "  " + src_reader[cols[i]] + "\n");
      }

      dstcmd.ExecuteNonQuery();

  }

我想知道,是否有更好,更有效的方法在不同数据库的表之间进行数据传输?或者这是唯一的方法?我知道在SqlConnection中,有一个SqlBulkCopy方法可以做到这一点,但OleDbConnection怎么样?有类似于SqlBulkCopy的东西吗?

任何帮助将不胜感激。谢谢。

c# sql sql-server ms-access ado.net
1个回答
1
投票

我也有类似你的问题,我将分享我要解决的功能,我希望它可以帮助你

Public bool InsertIntoDB(string tableName, DataTable _dataTable)
    {
        bool Result = false;
        DataTable ColumnsSQL = GetColumns(tableName);
        string CommandInsert = "Insert Into " + tableName + " (";
        string CommandValue = "";
        string commandSQL = "";
        DateTime Helpconstruct = new DateTime();
        String Word = "";
        String ValueToAdd = ""; 
        string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        FuncAuxC2C HELPPLEASE = new FuncAuxC2C();
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(null, conn);

        for (int k = 0; k < _dataTable.Rows.Count; k++)
        {

            for (int i = 0; i < ColumnsSQL.Rows.Count - 1; i++)
            {
                CommandInsert += ColumnsSQL.Rows[i][0].ToString();

                if (_dataTable.Rows[k][i].ToString() != "")
                {
                    ValueToAdd = _dataTable.Rows[k][i].ToString();
                    if (char.IsNumber(ValueToAdd[0]))
                    {
                        bool haveDigits = false;

                        foreach (char c in _dataTable.Rows[k][i].ToString())
                        {
                            if (c < '0' || c > '9')
                            {
                                haveDigits = true;
                                continue;
                            }

                        }

                        if (haveDigits == true && _dataTable.Rows[k][i].ToString().Contains("e+") && _dataTable.Rows[k][i].ToString().Contains(","))
                        {

                            _dataTable.Rows[k][i] = Decimal.Parse(_dataTable.Rows[k][i].ToString(), System.Globalization.NumberStyles.Float).ToString();

                        }
                    }
                }

                if (_dataTable.Columns[i].ColumnName.ToString() == "Data" && _dataTable.Rows[k][i].ToString() != "")
                {
                    //This is just to format date
                    ValueToAdd = HELPPLEASE.alterDataformat(_dataTable.Rows[k][i].ToString(), "yyyyMMdd", "-");

                }
                else if (_dataTable.Columns[i].ColumnName.ToString() == "tipificacao_datetime" && _dataTable.Rows[k][i].ToString() != "" )
                {
                    //This is just to format date 
                    ValueToAdd = HELPPLEASE.alterDataformat(_dataTable.Rows[k][i].ToString(), "yyyyMMddHHMMSS", "-");
                }
                else
                {
                    if (_dataTable.Rows[k][i].ToString().Length < 250)
                    {
                        ValueToAdd = _dataTable.Rows[k][i].ToString();
                    }
                    else
                    {
                        ValueToAdd = _dataTable.Rows[k][i].ToString().Substring(0, 250);
                    }
                }


                cmd.Parameters.AddWithValue("@" + ColumnsSQL.Rows[i][0].ToString(), SqlDbType.VarChar).Value = ValueToAdd;
                ValueToAdd = "";


                CommandValue += "@" + ColumnsSQL.Rows[i][0].ToString();

                if (ColumnsSQL.Rows.Count - 2 != i)
                {
                    CommandInsert += ", ";
                    CommandValue += ", ";
                }

            }



            commandSQL = CommandInsert + ") VALUES (" + CommandValue + ")";
            try
            {

                conn.Open();
                cmd.CommandText = commandSQL;
                cmd.ExecuteNonQuery();
                conn.Close();
                cmd.Parameters.Clear();

                commandSQL = "";
                CommandValue = "";
                CommandInsert = "";
                CommandInsert = "Insert Into " + tableName + " (";
                Result = true;
            }
            catch (Exception ex)
            {
                conn.Close();
                Result = false;
            }
            finally
            {
                cmd.Parameters.Clear();
                commandSQL = "";
                CommandValue = "";
                CommandInsert = "";
                CommandInsert = "Insert Into " + tableName + " (";
                conn.Close();
            }
        }


        return Result;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.