Niloy
Niloy

Reputation: 5

How to Display Data in C# form mysql table?

I am new on C# . I create a C# Console program and insert some data to MySql by following code .

string connection = "Server=localhost;Database=user_table;Uid=root;Pwd=";
MySqlConnection dbcon = new MySqlConnection(connection);
MySqlCommand cmd;
dbcon.Open();

cmd = dbcon.CreateCommand();
cmd.CommandText = "INSERt INTO user_table(user_name,amount)   VALUES(@user_name,@amount)";
cmd.Parameters.AddWithValue("@user_name","Niloy");
cmd.Parameters.AddWithValue("@amount", "456");
cmd.ExecuteNonQuery();

Now I want to retrieve this data and display in console application .
like This

Niloy 234

Joy 500

Minal 230

how can i do this ?

Upvotes: 0

Views: 6845

Answers (3)

Christos
Christos

Reputation: 53958

You have to do the opposite of that you have already done for the insertion of data.

// You sql command
MySqlCommand selectData;

// Create the sql command
selectData = dbcon.CreateCommand();

// Declare the sript of sql command
selectData.CommandText = "SELECT user_name, amount, FROM user_table";

// Declare a reader, through which we will read the data.
MySqlDataReader rdr = selectData.ExecuteReader();

// Read the data
while(rdr.Read())
{
    string userName = (string)rdr["user_name"];
    string amount = (string)rdr["amount"];

    // Print the data.
    Console.WriteLine(username+" "+amount);
}

rdr.Close();

Upvotes: 2

Khan
Khan

Reputation: 342

You can use gridview to display your data, Using the similar way you used to insert data into your Table.

string connection = "Server=localhost;Database=user_table;Uid=root;Pwd=";
MySqlConnection dbcon = new MySqlConnection(connection);
DataTable dt = new DataTable();

MySqlCommand cmd;
dbcon.Open();

cmd = dbcon.CreateCommand();
cmd.CommandText = "SELECT * from user_table";
adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dt);
Gridview1.DataSource=dt;
Gridview1.DataBind();

Upvotes: 0

apomene
apomene

Reputation: 14389

using (dbcon)
{
dbcon.Open();
cmd = dbcon.CreateCommand();
cmd.CommandText = "Select user_name,amount from   user_table";

 MySqlReader  sqlreader = cmd.ExecuteReader();

              while (sqlreader.Read())
              {
                 Console.WriteLine(sqlreader[0].ToString()+ " "+(sqlreader[1].ToString());
              }
              sqlreader.Close();

}

Upvotes: 0

Related Questions