C# 如何从web方法执行存储过程?
我想在Web方法中执行一个存储过程。它是存储过程中的select语句。我尝试了以下代码。然而,结果并不成功。结果应该返回1,但它总是返回-1。有人知道吗?请帮忙 以下是web服务。asmx代码:C# 如何从web方法执行存储过程?,c#,sql,web-services,stored-procedures,C#,Sql,Web Services,Stored Procedures,我想在Web方法中执行一个存储过程。它是存储过程中的select语句。我尝试了以下代码。然而,结果并不成功。结果应该返回1,但它总是返回-1。有人知道吗?请帮忙 以下是web服务。asmx代码: public class retrieveLoan : System.Web.Services.WebService { string constring = "Data Source=DIT-NB1260382;Initial Catalog=Experiment;
public class retrieveLoan : System.Web.Services.WebService
{
string constring = "Data Source=DIT-NB1260382;Initial Catalog=Experiment;Integrated Security=True";
SqlConnection myConn;
[WebMethod(Description="Simple Example")]
public int GetResult(int id, int age)
{
Int32 numberofRecords = 0;
System.Data.DataSet workDS = new System.Data.DataSet();
SqlCommand objCommand = default(SqlCommand);
//Create a command object
objCommand = new SqlCommand();
//prepare the command for retreiving
objCommand.CommandType = System.Data.CommandType.StoredProcedure;
objCommand.CommandText = "myprocedure2";
//open the connection
myConn = new SqlConnection(constring);
myConn.Open();
objCommand.Connection = myConn;
try
{
numberofRecords = (Int32)objCommand.ExecuteScalar();
return numberofRecords;
}
catch (Exception)
{
return -1;
}
finally
{
myConn.Close();
}
}
}
和我的存储过程:
ALTER PROCEDURE [dbo].[myprocedure2]
(
@puserid int,
@page int
)
AS
BEGIN
select * from userdet where userid = @puserid and age = @page
END
你提供的信息不多,很难回答,但这里有一个前进的方向: 将catch异常更改为catch Exception ex,然后通过返回该异常或在调试模式下分析该异常来查看该异常包含的内容
如果在调试模式下发布项目,则可以使用工具>附加到进程并连接到名为w3wp.exe的进程(如果有多个)连接到项目并进行调试,请在Type列下查找具有正确版本的.Net的存储过程。我认为不带参数执行此存储过程将返回异常 首先,为了让您看到异常,在catch声明中,您应该尝试显式地声明异常,如下所示:
try
{
numberofRecords = (Int32)objCommand.ExecuteScalar();
return numberofRecords;
}
catch (Exception ex)
{
//here you can enter into debug mode and see the exception "ex"
return -1;
}
finally
{
myConn.Close();
}
当您看到异常时,可以快速解决问题
接下来,应该将参数作为NULL添加到存储过程中,以便它们可以接受NULL值,或者,如果不接受,则必须在C代码中添加这些参数,并向它们发送一些值
此外,我还想指出一个事实,即如果要检索计数,应按如下方式修改存储过程:
ALTER PROCEDURE [dbo].[myprocedure2] ( @puserid int, @page int )
AS
BEGIN
select COUNT(userid) from userdet where userid = @puserid and age = @page
END
希望这能解决您的问题。您的查询是select*from userdet。ExecuteScalar所做的是选择第一个单元格值。现在您正在将其类型转换为int。如果您的第一个单元格值是字符串类型或其他类型。您肯定会收到一个错误。这将返回-1。请在select查询或计数中定义列名,如select count*from userdet。检查您的查询。您所说的结果不成功是什么意思。请定义您期望的内容?上面的代码不执行该命令。它总是返回-1,它不应该是case.pass参数,从codeobjCommand.Parameters.AddNew将参数传递到存储过程SqlParameter@puserid身份证件和objCommand.Parameters.AddNewSqlParameter@page,年龄@谢谢你。这就是我的代码所缺少的,并且现在工作正常。请把它贴出来作为答案,这样我就可以投票了。Tks。