复制表内容(表结构相同)

 public class sqlbulkcopyClass
    {
        public string sqlconString = "Data Source=.;Initial Catalog=TestDB;User ID=sa;Password=123456789";

        public void findAll()
        {
            try
            {
                using (SqlConnection sqlcon = new SqlConnection(sqlconString))
                {
                    sqlcon.Open();
                    SqlCommand com = new SqlCommand();
                    string sql = "SELECT [id],[name] FROM [TestDB].[dbo].[testTable]";
                    com.CommandText = sql;
                    com.CommandType = CommandType.Text;
                    com.Connection = sqlcon;
                    SqlDataReader reader = com.ExecuteReader();
                    using (SqlConnection sqlcon2 = new SqlConnection(sqlconString))
                    {
                        sqlcon2.Open();
                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlcon2))
                        {
                            bulkcopy.DestinationTableName = "testTable2";
                            try
                            {
                                bulkcopy.WriteToServer(reader);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                reader.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

 

posted @ 2014-12-12 16:30  临冰听雪丶  阅读(206)  评论(0编辑  收藏  举报