如何在 C# 中使用 openquery
How to use openquery in c#
我有一个 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 中 运行 时,我可以看到它 returns 需要 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);
}
我收到这样的错误:
The provider indicates that the user did not have the permission to perform the operation. Now I need to do something with this issue
我正在学习 openquery。有人可以指导吗?
首先,您没有在代码中的任何地方打开连接,因此出现错误。其次使用 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
文件中并在您的代码中读取它会更好。