반응형

C#에 MariaDB(MySQL) 데이터베이스를 연동해 보자.

 

NuGet Package Manager에서 MySql.Data를 설치한다.

 

위와 같은 데이터베이스를 준비한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using MySql.Data.MySqlClient;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string server = "192.168.171.200";
            string user = "root";
            string database = "member_db";
            string password = "1234";
            string connStr = $"server={server};user={user};database={database};port=3306;password={password}";
            MySqlConnection conn = new MySqlConnection(connStr);
 
            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();
                Console.WriteLine("Connected to MySQL.");
                // Perform database operations
 
                string sql = "SELECT * FROM member";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();
                // ExecuteReader to query the database.
                // ExecuteNonQuery to insert, update, and delete data.
 
                while (rdr.Read())
                {
                    Console.WriteLine($"ID: {rdr[0]}, Name: {rdr[1]}, Age: {rdr[2]}");
                }
                rdr.Close();
 
                sql = "SELECT name FROM member WHERE id='id2'";
                cmd = new MySqlCommand(sql, conn);
                object result = cmd.ExecuteScalar();
                // ExecuteScalar to return a single value.
 
                if (result != null)
                {
                    string name = Convert.ToString(result);
                    Console.WriteLine($"Name of id2: {name}.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
 
            conn.Close();
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

요청한 데이터를 표시한다.

※ 참고

MySQL Connector/NET Developer Guide

 

반응형
Posted by J-sean
: