0

此代码将数据从访问 SQL Server 表中复制出来。但是这段代码有一些问题。

  1. 此代码无法将数据从访问中复制到有数据的 SQL 服务器表。

我的 SQL Server 表有一些数据,我想在 SQL Server 表中的现有数据下添加来自访问的数据。

如何将数据添加到现有表?

  1. 无法从 access 2007 或 2010 读取数据。

如何从 access 2007/2010 读取数据

OpenFileDialog openfiledialog1 = new OpenFileDialog();
         openfiledialog1.Title = "select access file";

            openfiledialog1.Filter = "Access 2003 (*.mdb)|*.mdb|Access 2007|*.accdb";
            if (openfiledialog1.ShowDialog() == DialogResult.OK)
            {

                string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openfiledialog1.FileName;
                const string connectionStringDest = @"server=ahmad-pc\anfd;database = phonebook;Integrated Security = true";
                using (var sourceConnection = new OleDbConnection(connectionString))
                {
                    sourceConnection.Open();

                    var commandSourceData = new OleDbCommand("SELECT * from numberperson", sourceConnection);
                    var reader = commandSourceData.ExecuteReader();

                    using (var destinationConnection = new SqlConnection(connectionStringDest))
                    {
                        destinationConnection.Open();

                        using (var bulkCopy = new SqlBulkCopy(destinationConnection))
                        {


                            bulkCopy.ColumnMappings.Add("name", "nameperson"); //THIS A MAPPING REPLACE IT WITH YOUR NEED
                            bulkCopy.ColumnMappings.Add("family", "family1");
                            bulkCopy.DestinationTableName = "profile2";

                            try
                            {
                                bulkCopy.WriteToServer(reader);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                            finally
                            {
                                reader.Close();
                            }
                        }
                    }
                    MessageBox.Show("success");
                }

            }
4

1 回答 1

0

SQLBulkCopy only does Bulk inserts so any existing data should not be modified.

For MS Access > 2003 you'll need to use Microsoft ACE instead of JET

于 2013-04-10T13:08:11.270 回答