Rubz
Rubz

Reputation: 1

How to read data from a mysql table in c#?

When I start the program I always get this error: could not find specified column in results:firstname.

I changed "firstname" for any other column and it is giving me the same error. I have tested the connection also and the connection is properly written.

 public partial class frmDashboard : Form
{
    public frmDashboard()
    {
        InitializeComponent();
    }
    public frmDashboard(string user)
    {
        InitializeComponent();

        MySqlConnection connect = new MySqlConnection("Server=localhost;Database=mydb;user=root;Pwd=carolle;SslMode=none");
        MySqlCommand cmd = new MySqlCommand("select upper(customer.firstname) from mydb.customer where customer.email = '" + user + "';");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = connect;
        connect.Open();
        try
        {
            MySqlDataReader dr;
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                lblusername.Text = dr.GetString("firstname");

            }
            dr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

thank you in advance.

Upvotes: 0

Views: 54

Answers (1)

Zer0
Zer0

Reputation: 7354

That's due to your use of upper which changes the result set.

Using an alias with AS can fix this.

SELECT upper(customer.firstname) AS firstname FROM mydb.customer WHERE customer.email = '"+ user + "';"

Also you should be using parameters, not string concatenation, when creating queries for a wide variety of reasons including security and type safety.

If you prefer you can retrieve columns using indexes instead, changing

dr.GetString("firstname");

to

dr.GetString(0);

The column index corresponds to the ordering of columns in the SELECT statement.

Upvotes: 1

Related Questions