开发者

MySqlCommand().ExecuteReader().GetString() does not work

开发者 https://www.devze.com 2023-03-27 22:06 出处:网络
I\'m working with MySql in C# language. I\'m trying get some data out of my database. The fields are organized like:

I'm working with MySql in C# language. I'm trying get some data out of my database. The fields are organized like:

foo baa 
38737 22222 

I need to get value of foo if my hash is equal to baa I tried this: My code(not working)

 MySqlConnection con = new MySqlConnection("Server=localhost;Database=test;Uid=user;Pwd=pass;");
 con.Open();
 MySqlCommand cmd = new MySqlCommand();
 cmd.CommandText = string.Format("SELECT * FROM info WHERE baa = '{0}'", Hash); ;
 cmd.Connection = con;
 MySqlDataReader reader = cmd.ExecuteReader();
String res = reader.GetString(0); 

I'm getting the following error:

Invalid attem开发者_开发技巧pt to access a field before calling Read() 

Can someone point out my error? Thanks in advance.


You are missing a reader.Read() call:

 MySqlDataReader reader = cmd.ExecuteReader();
 while(reader.Read())
 {
     String res = reader.GetString(0); 
     //...
 }


Try:

string res;
using(MySqlDataReader reader = cmd.ExecuteReader())
{
    if(reader.Read())
        res = reader.GetString(0);
    else
        res = "not found";
}

If you change the SQL command to return a single value, for example:

"SELECT foo FROM info WHERE baa = '{0}' LIMIT 1"

then you can also use cmd.ExecuteScalar():

string res = cmd.ExecuteScalar().ToString();
0

精彩评论

暂无评论...
验证码 换一张
取 消