Sign in to follow this  
heroberlin

C# | Need a basic MySQL Programmcode

Recommended Posts

Hey guys,

iam pretty new to C# and dont know, how to connect to my MySQL database and do a simple select query.

It would be awesome, if a person could post a simple connect and select programm code, so I can work with it, and understand how to do it.

 

Thank you in advance.

Share this post


Link to post
Share on other sites
using MySql.Data.MySqlClient;

namespace Database
{
    class DatabaseTest
    {
        public string connectionString = "SERVER=127.0.0.1; DATABASE=db; UID=root; PASSWORD=pw;";

        /// <summary>
        /// Get the Name from Database
        /// </summary>
        /// <param name="id">primary key</param>
        /// <returns>the name</returns>
        public static string GetName(int id)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                MySqlCommand command = connection.CreateCommand();

                command.CommandText = "SELECT * FROM `mytable` WHERE id = @id LIMIT 1";

                command.Parameters.AddWithValue("@id", id);
                //command.Parameters.AddWithValue("@somemore", somemore);

                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    reader.Read();
                    return reader.GetString("name");
                }
            }
        }
    }
}

 

it is not testet but should work like this

Edited by notorious_nils
  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.