从MS Access批量导入并插入到Sql Server中

asp.net c# ms-access sqlbulkcopy sql-server

我想从MS Access数据库读取记录并插入到Sql server数据库,该过程应该是批量插入。我正在使用asp.net/vb.net

一般承认的答案

首先从Excel工作表中读取数据

connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/temp/") + "FileName.xlsx; Extended Properties=Excel 12.0;";

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
        DbDataAdapter adapter = factory.CreateDataAdapter();
        DbCommand selectCommand = factory.CreateCommand();
        selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
        DbConnection connection = factory.CreateConnection();
        connection.ConnectionString = connectionString;
        selectCommand.Connection = connection;
        adapter.SelectCommand = selectCommand;
        DataTable dtbl = new DataTable();
        adapter.Fill(dtbl);
 // Then use SQL Bulk query to insert those data

        if (dtbl.Rows.Count > 0)
{

 using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection))
        {
            bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
            bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
        bulkCopy.DestinationTableName = "DBTableName";
        bulkCopy.WriteToServer(dtblNew);
    }
}

热门答案

private void Synchronize()
{           
    SqlConnection con = new SqlConnection("Database=DesktopNotifier;Server=192.168.1.100\\sql2008;User=common;Password=k25#ap;");
    con.Open();
    SqlDataAdapter adap = new SqlDataAdapter("SELECT * FROM CustomerData", con);
    DataSet ds = new DataSet();
    adap.Fill(ds, "CustomerData");

    DataTable dt = new DataTable();
    dt = ds.Tables["CustomerData"];

    foreach (DataRow dr in dt.Rows)
    {                
        string File = dr["CustomerFile"].ToString();
        string desc = dr["Description"].ToString();

        string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=D:\\DesktopNotifier\\DesktopNotifier.accdb";

        OleDbConnection conn = new OleDbConnection(conString);
        conn.Open();
        string dbcommand = "insert into CustomerData (CustomerFile, Description) VALUES ('" + File + "', '" + desc + "')";
        OleDbCommand mscmd = new OleDbCommand(dbcommand, conn);

        mscmd.ExecuteNonQuery();                 
    }
}

private void Configuration_Load(object sender, EventArgs e)
{
    LoadGridData();
    LoadSettings();                     
}


许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因