1

此代码从 Access 文件 (.mdb) 中读取表信息并将表信息复制到 sql server 表中。此代码field1将 Access 文件复制到field1sql server 表中并复制field2field2...此代码正常工作,但我想要更改副本。我想将nameAccess 文件中的nameperson字段复制到 sql server 表中的字段。例如复制到sql server 表field1中的访问权限。field5我该怎么做呢?

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

        openfiledialog1.Filter = "Access 2003 (*.mdb)|*.mdb";
        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 id , name , family from numberperson", sourceConnection);
                var reader = commandSourceData.ExecuteReader();

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

                    using (var bulkCopy = new SqlBulkCopy(destinationConnection))
                    {
                        bulkCopy.DestinationTableName = "profile2";

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

        }
4

1 回答 1

0

请参见下面的示例,我添加了一个映射,用于将列名转换为 nameperson

[...]
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{             
 bulkCopy.ColumnMappings.Add("name", "nameperson"); //THIS A MAPPING REPLACE IT WITH YOUR NEED
 bulkCopy.DestinationTableName = "profile2";
[....]
于 2013-04-09T13:05:50.313 回答