In my case if I have a project including a database, firstly I always create a class where I define the constructors necessary for the certain database datas. For examples:
Constructors.cs:
namespace ExampleForMySqlDatabase{
class Course
{
private long id;
private string name;
private int length;
public Course(long id, string name, int length)
{
this.id = id;
this.name = name;
this.length = length;
}
public long Id { get => id; set => id = value; }
public string Name { get => name; set => name = value; }
public int Length { get => length; set => length = value; }
/*public override string ToString()
{
return $"id: {id}, etc..(To write out the datas, without this, it's only an object)";*/
}
}
}
After the correct datas in that file, next you need to create a new class file where you will read in the database and will do other methods using it. You need to download a certain extension, Tools->Nuget package manager->Manage Nuget packages for solution-> Browse->Download MySql.Data
ReadIn.cs
using MySql.Data.MySqlClient; //Don't forget to import it
namespace ExampleForMySqlDatabase
{
internal class ReadIn {
private List<Course> courses;
public ExampleForMySqlDatabase()
{
Loaded();
GetLongestCourse();
GetCourseLength();
}
public void Loaded()
{
string connStr = "server=localhost;user=root;database=The name of your database;port=3306;password=";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
conn.Open();
string sql = "SELECT id, name, length FROM The name of your database";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
courses = new List<Course>();
while (rdr.Read())
{
Course course = new Course(Convert.ToInt64(rdr.GetInt32(0)), rdr.GetString(1), rdr.GetInt32(2));
courses.Add(course);
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Environment.Exit(1);
}
conn.Close();
}
//this for looking for the longest for example
public void GetLongestCourse()
{
Course course = courses[0];
long longest = course.Id;
for (int i = 0; i < courses.Count; i++)
{
if (courses[i].Length > longest)
{
longest = course.Length;
course = courses[i];
}
}
Console.WriteLine($"Longest course: \n\t Name: {course.Name}}\n\t Length: {course.Length}, \n\tOktató: {course.Instructor}");
}
//or this you want to search for someone:
public void GetCourseLength()
{
Console.Write("Course name: ");
string course_name = Console.ReadLine();
for (int i = 0; i < courses.Count; i++)
{
if (courses[i].Name == course_name)
{
Console.WriteLine("Length of the course: " + courses[i].Length);
return;
}
}
Console.WriteLine("No courses found");
}
}
}
And in your main Program.cs file it should look like this:
internal class Program
{
static void Main(string[] args)
{
ExampleForMySqlDatabase exampleForMySqlDatabase= new ExampleForMySqlDatabase();
Console.ReadKey();
}
}
MySqlConnectorclass from NuGet.