Jump to content

C# | Need a basic MySQL Programmcode


heroberlin

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.

Link to comment
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
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...