使用存储过程从SQL Server返回数据
本文关键字:Server 返回 数据 SQL 存储过程 | 更新日期: 2023-09-27 18:14:14
我有麻烦返回数据从我的sql-server数据库到使用存储过程的aspx页面,并希望有人能突出我在哪里出错。
当我运行项目数据成功地输入到表中,但在以下页面(Confirm.aspx)上没有返回任何内容
Confirm.aspx.cs
using Devworks;
namespace OSQARv0._1
{
public partial class Confirm_Questionnaire : System.Web.UI.Page
{
OscarSQL b;
protected void Page_Load(object sender, EventArgs e)
{
b = new OscarSQL();
string qstname = b.GetQuestionName();
ReturnQstID.Text = qstname;
}// End Page_Load
} // Emd Class Confirm_Questionnaire
} // End Namespace
SQL.cs (App Code)
public OscarSQL()
{
_productConn = new SqlConnection();
_productConnectionString += "data source=mssql.database.co.uk; Initial Catalog=devworks_oscar;User ID=username;Password=password";
_productConn.ConnectionString = _productConnectionString;
}
public string GetQuestionName()
{
SqlCommand myCommand = new SqlCommand("GetQuestion", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
SqlParameter retval = myCommand.Parameters.Add("@QUESTTEXT", SqlDbType.VarChar);
retval.Direction = ParameterDirection.Output;
_productConn.Open();
string returnvalue = (string)myCommand.Parameters["@QUESTTEXT"].Value;
_productConn.Close();
return returnvalue;
}
存储过程USE [devworks_oscar]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [hgomez].[GetQuestion]
AS
/*SET NOCOUNT ON;*/
SELECT QuestionText FROM [Questions] WHERE QuestionnaireID = 21
RETURN
您没有执行进程,您正在设置它,但没有返回它。
string returnvalue = (string)myCommand.ExecuteScalar();
您的存储过程不使用输出参数来返回值,因此,使用ExecuteScalar():
string returnvalue = (string)myCommand.ExecuteScalar();
返回值是存储过程返回的值,通常为整数值,有时用于驱动业务逻辑或错误条件。在您的示例中,您需要返回的数据,而不是返回值。因此,如果查询返回单个值,则使用ExecuteScalar;如果查询返回一条或多条数据记录,则使用ExecuteReader。ExecuteNonQuery通常用于插入/更新和/或删除操作。
ExecuteScalar() is a good idea if you know there is only one occurance of that record in the database, ExecuteScalar if I am not mistaken only returns the first record or occurance it finds.. you could use a datareader and do datareader.ExecuteReader() this is forward only but there are ways to make it biDirectional hehe... :) anyway if you want to loop thru the results use ExecuteReader() if you want to execute a StoredProceduere with UDATE,DELETE, or INSERT use reader.ExecuteNonQuery().
Hope this helps.