从iis上的webservice访问数据库 [英] access database from webservice on iis
问题描述
我创建了一个Web服务,连接到我本地计算机上的SQL Server 2008 R2中托管的数据库,并对其进行了一些操作。
这是Web服务中的连接字符串:
I made a web service that connects to a database hosted in SQL Server 2008 R2 on my local computer, and makes some operations on it.
This is the connection string in the web service:
conn = new SqlConnection("Data Source=amir-pc\\SQLEXPRESS;User Id=sa;Password=1234; Initial Catalog=Election;Integrated Security=True");
它运行良好并成功访问数据库并运行正确。
现在我想将此Web服务添加到IIS。
我在Windows 7上成功将其添加到IIS并且可以从浏览器运行它。
localhost / election_service / service.asmx
但是当我试图调用一个检查连接的函数,它失败了,我不知道为什么。这是功能:
It works well and successfully accesses the database and runs right.
Now I want to add this web service to IIS.
I successfully added it on Windows 7 to the IIS and can run it from the browser.
localhost/election_service/service.asmx
but when I tried to call a function that checks the connection, it failed, and I don''t know why. This is the function:
[WebMethod]
public string Check_conn()
{
try
{
conn.Open();
conn.Close();
return "ok";
}
catch
{
return "failed";
}
}
我是否需要修改才能访问数据库?
Is there any modification I must to do to be able to access the database?
推荐答案
Amir
您是否使用上述连接字符串实例化了conn对象?
还要检查连接是否已经打开,因为如果连接已经打开,conn.open将抛出InvalidOperationException异常,导致函数在catch语句中返回false。理想情况下请检查:
Amir
Have you instantiated the conn object with the above mentioned connection string?
Also do check if the connection is already open or not, since if the connection is already open the conn.open will throw InvalidOperationException exception resulting in your function returning false in catch statement. So ideally check this:
public string Check_conn()
{
try
{
if(!conn.IsOpen)
{
conn.Open();
conn.Close();
}
return "ok";
}
catch
{
return "failed";
}
}
问候
Pawan
Regards
Pawan
>
这篇关于从iis上的webservice访问数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!