【问题标题】:How to use openquery in c#如何在 C# 中使用 openquery
【发布时间】:2015-04-22 11:09:38
【问题描述】:

我有一个 openquery SQL 脚本:

Select * from openquery([oak],'
SELECT LicenseKey, SUM(PaymentAmount)as Payments
FROM vw_ODBC_actv_Payments pt 
WHERE MONTH(pt.EntryDate) = 2 and
YEAR(pt.EntryDate) = 2015 
GROUP BY LicenseKey
')

当我从 SSMS 运行它时,我可以看到它返回了预期的 n 行。

但是,当我使用相同的连接属性来获取 C# 控制台应用程序的 DataSet 中的数据时:

    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand pcmd= new SqlCommand();
    DataSet ds= new DataSet();
    OpenConnection();
    pcmd.Connection = new SqlConnection("Data source=IP adress of the server;Initial Catalog=master; user ID=***; password=***");
    cmd.CommandText = "Select * from openquery([oak],'" +
    "SELECT LicenseKey, SUM(PaymentAmount)as Payments" +
    "FROM vw_ODBC_actv_Payments pt " +
    "WHERE MONTH(pt.EntryDate) = 2 and" +
    "YEAR(pt.EntryDate) = 2015" +
    "GROUP BY LicenseKey')";
try
{
    da.SelectCommand = pcmd;
    da.Fill(ds); //here comes the error
}
catch (Exception ex)
{
    throw new Exception("DBUtils.ExecuteReader():" + ex.Message);
}

我收到这样的错误:

提供者表示用户没有权限 执行操作。现在我需要解决这个问题

我只是在学习 openquery。有人可以指导吗?

【问题讨论】:

  • 你没有从上面的代码中打开连接..你也没有声明ds
  • @Izzy - 这是我项目中的代码摘录。连接和数据集由自定义函数提供。当我打开连接时,我的问题就来了。

标签: c# database-connection openquery


【解决方案1】:

首先,您没有在代码中的任何位置打开连接,因此会出现错误。其次用using 块清理你的代码。因此,假设查询按要求工作,您可以执行类似的操作。

using(SqlConnection con = new SqlConnection("Connection String Here"))
    {
        string myQuery = "Your Query";
        using(SqlCommand cmd = new SqlCommand(myQuery, con))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                con.Open();
                sda.SelectCommand = cmd;
                DataSet ds = new DataSet();
                sda.Fill(ds);
            }
        }
    }

注意:如果您将connectionString 存储在您的config 文件中并在您的代码中读取它会更好。

【讨论】:

  • 还是有同样的异常。
  • 在您的connectionString 中尝试providerName="System.Data.SqlClient"
  • 试试这个.. 在桌面上创建一个空文本文件,使用.udl 扩展名命名它。创建后,双击它,您将看到一个 GUI 打开以指导您构建连接字符串。单步执行,如果成功则单击测试连接,然后在文本编辑器中打开 udl 文件并复制 connectionstring 并将其粘贴到您的代码中
  • Izzy - 您的解决方案帮助我连接到链接服务器。我相信有一些限制 - The provider indicates that the user did not have the permission to perform the operation. Now I need to do something with this issue
  • 错误确实不言自明。您的权限是如何设置的等,您需要检查然后从那里获取。我提供的解决方案回答了您的原始问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多