2012-08-29 74 views
0

我需要從不同數據庫檢索行。如何從差異數據庫檢索數據併合併到單個數據表中?從不同數據庫檢索行

我需要檢索這些行,並將其導出到Excel

請幫我找到一個解決方案。

這裏是我的代碼:

public void Execute(IJobExecutionContext context) 
    { 
     try 
     { 
      logger.InfoFormat("....blcExportExcel start run.... "); 
      SqlCommand com1 = null; 
      //SqlCommand comCount = null; 
      SqlConnection con1 = null; 

      //--for microsoft 2003-- 
      string strDownloadFileName = "E://lewre/excel/color/delete_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls"; 
      string oleDbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDownloadFileName + ";Extended Properties='Excel 8.0;HDR=Yes'"; 
      //**for microsoft 2003** 

      //--for microsoft 2007-- 
      //string strDownloadFileName = "E://lewre/excel/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; 
      //string oleDbConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strDownloadFileName + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'"; 
      //**for microsoft 2007** 

      //--Export product for icenter 25/7/2012-- 
      string query = @" 

        select lewre_article.SKU_CODE,icenter_acStockCompany.AcStockID 
       from 
       [LEWREDB].[dbo].[LEWRE.PRODUCT] as lewre_article 
       left join [iCenter].[dbo].[AcStockCompany] as icenter_acStockCompany 
       on (lewre_article.SKU_CODE = icenter_acStockCompany.AcStockID) 
       where icenter_acStockCompany.AcStockID is null 
      "; 

      //**Export product for icenter 25/7/2012** 
      con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["iCenterConnectionString"].ConnectionString); 
      con1.Open(); 

      com1 = new SqlCommand(query, con1); 
      DataTable dt = new DataTable(); 
      SqlDataAdapter ada = new SqlDataAdapter(com1); 
      ada.Fill(dt); 

      //--If no record then return-- 
      if (dt.Rows.Count == 0) 
      { 
       return; 
      } 
      //**If no record then return** 

      using (OleDbConnection conn = new OleDbConnection(oleDbConnection)) 
      { 
       // Create a new sheet in the Excel spreadsheet. 
       string createTable = " "; 
       createTable += " create table Query(SKU_CODE varchar(50) , AcStockID varchar(50))"; 
       // Create a new sheet in the Excel spreadsheet. 
       OleDbCommand cmd = new OleDbCommand(createTable, conn); 

       // Open the connection. 
       conn.Open(); 

       // Execute the OleDbCommand. 
       cmd.ExecuteNonQuery(); 

       cmd.CommandText = @"INSERT INTO Query (
       SKU_CODE, AcStockID) 

       values (?,?) "; 
       // Add the parameters. 
       cmd.Parameters.Add("SKU_CODE", OleDbType.VarChar, 50, "SKU_CODE"); 
       cmd.Parameters.Add("AcStockID", OleDbType.VarChar, 50, "AcStockID"); 



       // Initialize an OleDBDataAdapter object. 
       OleDbDataAdapter da = new OleDbDataAdapter("select * from Query ", conn); 

       // Set the InsertCommand of OleDbDataAdapter, 
       // which is used to insert data. 
       da.InsertCommand = cmd; 
       // Changes the Rowstate()of each DataRow to Added, 
       // so that OleDbDataAdapter will insert the rows. 

       foreach (DataRow dr in dt.Rows) 
       { 
        dr.SetAdded(); 
       } 

       // Insert the data into the Excel spreadsheet. 
       da.Update(dt); 
      } 

      JobKey jobKey = context.JobDetail.Key; 
      logger.InfoFormat("blcPosExcel : {0} executing at {1}", jobKey, DateTime.Now.ToString("r")); 
      logger.InfoFormat("excel post run finnish "); 



     } 
     catch (Exception ex) 
     { 
      logger.Error(ex.Message); 
      throw; 

     } 
    } 
} 

我的ConnectionString

<!--Koo Testing Server--> 
    <add name="LEWREDBConnectionString" connectionString="Data Source=NATE-PC\SQLEXPRESS2008R2;Initial Catalog=LEWREDB_WEB_TEST;User ID=user1;Password=user" providerName="System.Data.SqlClient" /> 
    <add name="LEWREDBEntities" connectionString="metadata=res://*/ClassModel.LinQLewre.csdl|res://*/ClassModel.LinQLewre.ssdl|res://*/ClassModel.LinQLewre.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=NATE-PC\SQLEXPRESS2008R2;Initial Catalog=LEWREDB_WEB_TEST;Persist Security Info=True;User ID=user1;Password=user;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /> 
    <add name="iCenterConnectionString" connectionString="Data Source= NATE-PC\SQLEXPRESS2008R2;Initial Catalog=iCenter_Testing;User ID=user2;Password=user" providerName="System.Data.SqlClient" /> 
    <!--Koo Testing Server--> 

錯誤,那是我得到:

無法打開數據庫 「iCenter_Testing」 由登錄請求。 登錄失敗。用戶'user2'的登錄失敗。

+1

這意味着......在'iCenter_Testing' DB'user2'是無效的...... –

回答

1

檢查數據庫iCenter_Testing中是否存在user2,並且該用戶具有正確的權限。如果您連接到數據庫,就可以該用戶是否存在運行下面的代碼看:

SELECT name FROM master.dbo.syslogins WHERE name = 'user2'

但是,如果你能使用user2登錄到數據庫中,它可能是一個情況沒有iCenter_Testing數據庫的必要權限。

SELECT HAS_DBACCESS('iCenter_Testing');

上面的SQL將返回101表示用戶有權訪問數據庫。

要了解哪些數據庫用戶有權訪問過,你可以運行下面的代碼:

SELECT [Name] as DatabaseName 
FROM master.dbo.sysdatabases 
WHERE ISNULL(HAS_DBACCESS([Name]),0)=1 
ORDER BY [Name] 
+1

作爲SQL的Server 2005,你應該停止使用'sysdatabases'和所有那些舊式的視圖(像'sysobjects')。相反,使用'sys'目錄視圖模式中的'sys.databases'。 –

+0

@marc_s:注意到,但沒有提及正在使用哪個SQL Server版本,所以玩起來很安全。 –