1

here is my code:

private void searchInDatabase()
{
    MySqlConnection c = new MySqlConnection("datasource=localhost; username=root; password=123456; port=3306");
    MySqlCommand mcd;
    MySqlDataReader mdr;
    String query;

    try 
    {
        c.Open();
        query = "SELECT * FROM test.classmates WHERE first_name ='"+searchName.Text+"'";
        mcd = new MySqlCommand(query, c);
        mdr = mcd.ExecuteReader();
        if(mdr.Read())
        {
            firstName.Text = mdr.GetString("first_name");
            middleName.Text = mdr.GetString("middle_name");
            lastName.Text = mdr.GetString("last_name");
            age.Text = mdr.GetString("age");
        }
        else
        {
            MessageBox.Show("Result Not Found");
        }
    }
    catch(Exception error)
    {
        MessageBox.Show("Error: "+error.Message);
    }
    finally
    {
        c.Close();
    }
}

I would like to ask for a help if I have missed on anything or I am doing it wrong. If you have free time, I will much appreciate it if you will comment the perfect way to do I implement this problem: I want to get data from MySQL then put it in a textbox.

depperm
  • 10,606
  • 4
  • 43
  • 67
n00b
  • 192
  • 13
  • 3
    What error / problem you have now? Please read [**How-to-Ask**](http://stackoverflow.com/help/how-to-ask) And here is a great place to [**START**](http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/) to learn how improve your question quality and get better answers. – Juan Carlos Oropeza Jul 19 '16 at 14:43
  • As a side note you should use a parameter for searchName in your query, here's a good explanation: http://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements, also could you include where firstName, middleName, lastName, and age are defined? – chandler Jul 19 '16 at 14:47
  • My problem is I can't get data from my database then output the data to my c# program, specifically into a textbox. – n00b Jul 19 '16 at 15:24

2 Answers2

0

According to MSDN you need to pass the column number as parameter

public override string GetString(int i)

So try to pass the column number (starts from 0) of your column name. Assuming the first_name is the first column of your table then

firstName.Text = mdr.GetString(0);

UPDATE

Try to use MySqlConnectionStringBuilder

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "serverip/localhost";
conn_string.UserID = "my_user";
conn_string.Password = "password";
conn_string.Database = "my_db";
MySqlConnection conn = new MySqlConnection(conn_string.ToString();
Christlin Panneer
  • 1,599
  • 2
  • 19
  • 31
0

First of all look at this sample of connection string and change your connection string: 'Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPasswor;' If connection is OK send erorr message or full exception.

Evgenii
  • 183
  • 1
  • 5