简体   繁体   English

用C#构建的Web Service从mySQL数据库中检索数据

[英]Web Service built in C# to retrieve data from mySQL database

I am trying to build a web service in .NET, which will retrieve data from a mySQL database. 我正在尝试在.NET中构建一个Web服务,它将从mySQL数据库中检索数据。 This web service will later on be combined with a windows form where this data will be displayed. 此Web服务稍后将与将显示此数据的Windows窗体组合。

Till now, I have the database ready, the connection between the database and the web service has been made and the form is ready as well. 到现在为止,我已准备好数据库,数据库和Web服务之间已建立连接,表单也已准备就绪。

However, I am unable to retrieve particular bits of information from the table itself. 但是,我无法从表本身检索特定的信息。 Can anyone help me to figure out what my next steps should be? 任何人都可以帮我弄清楚我的下一步应该是什么? I have googled a lot on this issue but I was still unable to find a good tutorial regarding this issue...if you have any in mind then can you please post the link as well? 我在这个问题上搜索了很多,但我仍然无法找到关于这个问题的好教程...如果你有任何想法,那么你也可以发布链接吗? Thanks in advance! 提前致谢!

EXTRA INFORMATION: Suppose a sample table called "testdata" which has three columns in it ("id", "name", "age"). 附加信息:假设一个名为“testdata”的样本表,其中有三列(“id”,“name”,“age”)。 How can I extract the name and the age and display them on the form? 如何提取名称和年龄并在表单上显示?

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

namespace WebService2
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {



        private void connectoToMySql()
        {

            string connString = "SERVER=localhost" + ";" +
                "DATABASE=testdatabase;" +
                "UID=root;" +
                "PASSWORD=password;";

            MySqlConnection cnMySQL = new MySqlConnection(connString);

            MySqlCommand cmdMySQL = cnMySQL.CreateCommand();

            MySqlDataReader reader;

            cmdMySQL.CommandText = "select * from testdata";

            cnMySQL.Open();

            reader = cmdMySQL.ExecuteReader();


           //-----------------------------------------------------------
           // This is the part where I should be able to retrieve the data from the database
           //-----------------------------------------------------------               


            cnMySQL.Close();
        }


    }
}

Create a method that is public, marked with the WebMethodAttribute, and returns a DataTable (if you consumer is a .net client). 创建一个公共的方法,用WebMethodAttribute标记,并返回一个DataTable(如果您的使用者是.net客户端)。 Have the consumer call that method and do whatever you want with the DataTable. 让消费者调用该方法并使用DataTable执行任何操作。

[System.Web.Services.WebMethod]
public DataTable connectoToMySql()
{
    string connString = "SERVER=localhost" + ";" +
        "DATABASE=testdatabase;" +
        "UID=root;" +
        "PASSWORD=password;";

    MySqlConnection cnMySQL = new MySqlConnection(connString);

    MySqlCommand cmdMySQL = cnMySQL.CreateCommand();

    MySqlDataReader reader;

    cmdMySQL.CommandText = "select * from testdata";

    cnMySQL.Open();

    reader = cmdMySQL.ExecuteReader();

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


    cnMySQL.Close();

    return dt;
} 

You have a couple of options here. 你有几个选择。

First, you can get rid of the DataReader and instead use a DataAdapter to fill a DataSet and return the full DataSet. 首先,您可以摆脱DataReader,而是使用DataAdapter填充DataSet并返回完整的DataSet。 (This might be the simplest, but it's the least friendly if you intend to ever call it from a non-.NET app.) (这可能是最简单的,但如果您打算从非.NET应用程序调用它,那么它是最不友好的。)

Second, you can actually use the reader, looping through the data to populate whatever business object your function is supposed to return... But you haven't given us enough into to tell you how to do it. 其次,您实际上可以使用阅读器,循环遍历数据以填充您的函数应该返回的任何业务对象...但是您还没有给我们足够的信息来告诉您如何执行此操作。

Either way, your function isn't returning ANYTHING now, and you haven't even marked is at a WebMethod... I strongly recommend going back to MSDN for examples. 无论哪种方式,你的函数现在都没有返回任何内容,你甚至没有在WebMethod上标记过...我强烈建议回到MSDN获取示例。 Or watch this video: http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-and-call-a-simple-web-service-in-aspnet 或观看此视频: http//www.asp.net/web-forms/videos/how-do-i/how-do-i-create-and-call-a-simple-web-service-in-aspnet

Right now, your code and question indicates you don't yet understand the basics (there's nothing wrong with that - we all start somewhere), and this video will cover them. 现在,你的代码和问题表明你还没有理解基础知识(没有任何问题 - 我们都从某个地方开始),这个视频将覆盖它们。 As it stands, you need more assistance than we can provide in this forum , short of showing you where to find the info you need. 目前,您需要的帮助超出我们在此论坛中提供的帮助,而不是向您展示在哪里可以找到您需要的信息。 (Which I hope I've done.) (我希望我已经完成了。)

When you call the webservice, you need to call a method that will return data. 当您调用Web服务时,您需要调用将返回数据的方法。

You'd need parts like: 你需要的部分如:

[WebMethod()]
public UserRecord[] GetUserRecords() 
{ 

  List<UserRecod> userRecords = new List<UserRecord>();

    string connString = "SERVER=localhost" + ";" + 
        "DATABASE=testdatabase;" + 
        "UID=root;" + 
        "PASSWORD=password;"; 

    //introduce a connection with mySQL database 
    using(MySqlConnection cnMySQL = new MySqlConnection(connString))
    {
      //create your mySql command object 
      using(MySqlCommand cmdMySQL = cnMySQL.CreateCommand())
      { 
            //set the command text (query) of the mySQL command object 
            cmdMySQL.CommandText = "select * from testdata"; 
            cmdMySql.CommandType = CommandType.Text;
            cmdMySql.Connection = cnMySql;

            cnMySql.Open();
            //create your mySQL reader object 
            using(MySqlDataReader reader = cmdMySQL.ExecuteReader())
            {

                while(reader.Read())
                {
                    userRecords.Add(new UserRecord() { Id = reader.GetInt32(reader.GetOrdinal("id"), Name = reader.GetString(reader.GetOrdinal("name")}
                }

            }

    }

  }

  return userRecords.ToArray();

}

You might look to return an object like: 您可能希望返回一个对象,如:

public class UserRecord
{

    public UserRecord() { }

    public int Id { get; set; }

    public string Name { get; set; }

}

Be aware that this is just an example, you probably wouldn't structure your code this way. 请注意,这只是一个示例,您可能不会以这种方式构建代码。 For example, you might actually put a method on UserRecord that returns the user records, and this will interact with a Data Access class or similar to connect to the database. 例如,您实际上可能会在UserRecord上放置一个返回用户记录的方法,这将与数据访问类或类似方法交互以连接到数据库。 That way you could share UserRecord everywhere. 这样你就可以在任何地方分享UserRecord。

You might also want to consider what you are returning. 您可能还想考虑要返回的内容。 A DataTable is fine for .Net clients, but is quite heavy. DataTable适用于.Net客户端,但非常繁重。 A light-weight object containing just the data you need is preferable. 最好只包含您需要的数据的轻量级对象。

Note that you'd also want to wrap your DAO calls in Using statements. 请注意,您还希望将DAO调用包装在Using语句中。 This ensures the data access objects are properly disposed of when you leave the last bracked of the using statement (or if an exception is thrown). 这样可以确保在离开最后一个使用语句时(或者抛出异常时)正确处理数据访问对象。

After you get the reader, you can loop through each row with with: 获得阅读器后,您可以使用以下内容遍历每一行:

while (reader.Read())
{
   int id = (Int32)reader["MyId"];
   string name = reader["Name"] as String;
}

You can also use the reader to populate a DataSet object, which could be helpful if you just want to return that from your web service: 您还可以使用阅读器填充DataSet对象,如果您只想从Web服务返回该对象,这可能会有所帮助:

DataSet ds = new DataSet();
ds.Load(reader, LoadOption.OverwriteChanges, "TestData");

I'd also recommend you close the Reader when you're done with it: 我还建议您在完成阅读后关闭阅读器:

reader.Close();

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

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