[英]Display query result depending on user input
我正在使用C#.NET中的代碼創建一個將接受特定輸入的Web服務。 然后它將連接到數據庫,根據提供的輸入,必須從我的表中獲取整個結果並相應地顯示。
但是,我不熟悉C#.NET,所以我無法正確實現我的代碼。 有人可以幫幫我嗎
以下是我到目前為止所做的事情:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace test3
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String GetAttendance(String rollno)
{
String result="";
try
{
using (SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123"))
{
myConnection.Open();
using (SqlCommand myCommand = new SqlCommand())
{
myCommand.Connection = myConnection;
myCommand.CommandText = "SELECT COUNT(*) FROM studentdata WHERE rollno = @rollno";
myCommand.Parameters.Add("@rollno", SqlDbType.VarChar).Value = rollno;
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
result = myReader.ToString();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "an error occured";
}
return result;
}
}
}
如果我運行此代碼,我得到輸出為“System.Data.SqlClient.SqlDataReader”這不是我想要的
不要為此使用數據讀取器只有一個行數,所以使用ExecuteScalar()
並使用int作為結果的類型:
int result = Convert.ToInt32(myCommand.ExecuteScalar());
(或者,您可以使用result = myReader.GetInt32(0).ToString();
獲取當前查詢的字符串值result = myReader.GetInt32(0).ToString();
- 盡管不這樣做)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.