Ale
Ale

Reputation: 27

How to convert a MySql selection into an string? C#

Convert MySQL Select to an String. To take the ip

MySqlCommand o = connection.CreateCommand();
o.CommandText = "SELECT Ip FROM Sma.Serv WHERE Id=1";
MySqlDataReader r = o.ExecuteReader();
PingReply rep1 = serv.Send("print Ip from DataBase Here", 1000);

Upvotes: 0

Views: 139

Answers (3)

Nicolas C
Nicolas C

Reputation: 235

o.CommandText = "SELECT Ip FROM Sma.Serv WHERE Id=1";
MySqlDataReader r = o.ExecuteReader();
string _ip;

then you expect 1 result or 0, you can use an 'if'

if(r.Read())
{
    _ip = r[0].ToString();
}

if you may have more than 1 result you have to use a while loop

while(r.Read())
{
     _ip = r[0].ToString();
}

in this case, and if you wan't to do something only if your request return one ip, you can add a counter in you loop while

int i = 0;
while(r.Read())
{
     _ip = r[0].ToString();
     i++;
}
if(i==1)
{
     // do your stuff
}
else {//do another stuff}

and don't forget to close the datareader after!!!

r.Close();

Upvotes: 0

Sherantha
Sherantha

Reputation: 482

You can do it like this.

o.CommandText = "SELECT Ip FROM Sma.Serv WHERE Id=1";
MySqlDataReader r = o.ExecuteReader();
string _ip;
while(r.Read())
{
   _ip = r["Ip"].ToString();
}
if(_ip != "")
{
  //do your task
}

Upvotes: 0

weeksdev
weeksdev

Reputation: 4355

Check out the example here on msdn

And here is an example using similar code to what you've written above to retrieve the first records ip via the GetString method:

o.CommandText = "SELECT Ip FROM Sma.Serv WHERE Id=1";
MySqlDataReader r = o.ExecuteReader();
if (r.HasRows)
{
    r.Read();
    var firstRecordIp = r.GetString(0);
}

Please note, you could also use a DataAdapter to fill the data to a DataTable.

Upvotes: 2

Related Questions