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;

        }
    }
}

我的连接字符串

   <!--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”登录失败。

4

1 回答 1

1

检查数据库user2中是否存在iCenter_Testing以及用户是否具有正确的权限。如果连接数据库,可以运行以下代码查看用户是否存在:

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

但是,如果您能够使用 登录到数据库user2,则可能是没有必要的iCenter_Testing数据库权限。

SELECT HAS_DBACCESS('iCenter_Testing');

上面的 SQL 将返回一个1or 01表示用户有权访问数据库。

要找出用户也可以访问哪些数据库,您可以运行以下代码:

SELECT [Name] as DatabaseName 
FROM master.dbo.sysdatabases
WHERE ISNULL(HAS_DBACCESS([Name]),0)=1
ORDER BY [Name]
于 2012-08-29T08:28:34.280 回答