Jeppe Christensen Jeppe Christensen - 1 month ago 6
MySQL Question

IEnumerable print out single entity from a mySQL connection

First of all, im a total beginner with this stuff, so bear with me here.

So, i want to fetch data from a Webservice from xCode. Therefore im building a webservice that can get data in mySql and present them (when im done) in json format.

However, right now, im not very far...
I have set up my database, and it is live on a server.

I have made the connection string in my web.config, and i have in the code below tried to establish a connection, to try and get and present the row where the ID = 1.. consequently i want it to display all entities in my database, but this is good for a start.

I think my connection is okay, (don't know how to test it, other than just make it print something from the database on my page)

However, i get an error in my code saying

cannot implicitly convert type string to 'system.collections.generic.ienumerable<string>'


you might say that its an error solved another place on stackoverflow, but none the less i cant seem to understand how to solve it.

MySql.Data.MySqlClient.MySqlConnection mySqlConnection;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;

public IEnumerable<String> Get()
{

String connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySql"].ToString();
mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(connString);

mySqlConnection.Open();
queryStr = "SELECT * FROM `CustomerDb` WHERE 'ID' = '1'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, mySqlConnection);
cmd.ExecuteReader();
mySqlConnection.Close();

return queryStr;
}


Thank you very much in advance.

UPDATE

I have made these constructors for my db entities

public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Category { get; set; }

Answer

The problem is you are trying to return a string where your return type of the function Get() is IEnumerable. I guess you need to get what you select from the table but not your query string, right?

MySql.Data.MySqlClient.MySqlConnection mySqlConnection;
    MySql.Data.MySqlClient.MySqlCommand cmd;
    String queryStr;

public IEnumerable<String> Get()
{

    String connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySql"].ToString();
    mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(connString);

    mySqlConnection.Open();
    queryStr = "SELECT * FROM `CustomerDb` WHERE 'ID' = '1'";
    cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, mySqlConnection);
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        yield return reader["Name"]; // Assume you want name in your result.
    }

    mySqlConnection.Close();

}
Comments