简体   繁体   English

使用ASP.NET WEB Services返回列的总和

[英]Return sum of a column using ASP.NET WEB Services

I have been tring to return the sum of a column using this web service but it does not work .Please Help.Thank You. 我一直在使用这个Web服务返回列的总和,但它不起作用。请帮助。谢谢。 I am using Visual Studio 2010.It Just Keeps on Returning an error.System.InvalidOperationException: There was an error generating the XML document. 我正在使用Visual Studio 2010.It只是继续返回error.System.InvalidOperationException:生成XML文档时出错。 ---> System.InvalidOperationException: Cannot serialize the DataTable. ---> System.InvalidOperationException:无法序列化DataTable。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using MySql.Data.MySqlClient;

namespace Transcript_System
{
    /// <summary>
    /// Summary description for check
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.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 check : System.Web.Services.WebService
    {

        [WebMethod]
    public DataTable connectoToMySql()
    {
        string connString = "SERVER=localhost" + ";" +
            "DATABASE=transcriptdb;" +
            "UID=root;" +
            "PASSWORD=;";

        MySqlConnection cnMySQL = new MySqlConnection(connString);

        MySqlCommand cmdMySQL = cnMySQL.CreateCommand();

        MySqlDataReader reader;

        cmdMySQL.CommandText = "SELECT SUM( Score ) FROM faculty_table WHERE Mat_No='PSC0908888'";

        cnMySQL.Open();

        reader = cmdMySQL.ExecuteReader();

        DataTable dt = new DataTable();
        dt.Load(reader);


        cnMySQL.Close();

        return dt;
    } 
            }
        }

You can send the data as a xml string from a dataset by DataSet.GetXml() 您可以通过DataSet.GetXml()将数据作为xml字符串从数据集发送

And than the user can deserialize it with DataSet.ReadXml() 并且用户可以使用DataSet.ReadXml()反序列化它

And get the datatable from the dataset by DataSet.Tables 并通过DataSet.Tables从数据集中获取数据表

You don't need a table, you are simply getting a single value from the database, use Execute Scalar instead. 您不需要表,只需从数据库中获取单个值,而是使用Execute Scalar。

cnMySQL.Open();
string sum = mySqlcommand.ExecuteScalar();
cnMySQL.Close();
return sum;

and change your method to return a string instead 并更改您的方法以返回字符串

Your web method is returning an object of type DataTable. 您的Web方法返回DataTable类型的对象。 Perhaps you want to change that to return just an int/string with the value of the count, and not the fetched Datatable instance! 也许你想改变它只返回一个带有count值的int / string,而不是返回获取的Datatable实例!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM