4

I am trying to build a web service in .NET, which will retrieve data from a mySQL database. This web service will later on be combined with a windows form where this data will be displayed.

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.

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"). 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();
        }


    }
}
3
  • I think you have excessive comments. Commented Dec 2, 2011 at 21:24
  • and the examples on msdn.microsoft.com/en-us/library/… don't help you? Commented Dec 2, 2011 at 21:26
  • Yeah this is sort of an old habit of mine...in case I want to look back at codes later :) I have removed them from the code now... Commented Dec 2, 2011 at 21:26

4 Answers 4

6

Create a method that is public, marked with the WebMethodAttribute, and returns a DataTable (if you consumer is a .net client). Have the consumer call that method and do whatever you want with the 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;
} 
Sign up to request clarification or add additional context in comments.

Comments

2

When you call the webservice, you need to call a method that will return data.

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. That way you could share UserRecord everywhere.

You might also want to consider what you are returning. A DataTable is fine for .Net clients, but is quite heavy. 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. 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).

Comments

2

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. (This might be the simplest, but it's the least friendly if you intend to ever call it from a non-.NET app.)

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. 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

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.)

Comments

1

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 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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.