19. 4. 4.

C#으로 MYSQL 연동

C# 에서 MySql을 연동하려면 사전 준비가 필요.

기준 : 비주얼스튜디오
1. 프로젝트 생성할 때 프레임워크를 4.5.2로 생성
2. 솔루션 탐색기의 프로젝트명에서 우클릭
3. NuGet 패키지 관리
4. MySql.Data 설치(8.0.15 버전으로 설치함)

insert,update,delete
using MySql.Data.MySqlClient;

namespace MySql
{
    class Program
    {
        static void Main(string[] args)
        {
            // Sql 연결정보(서버:127.0.0.1, 아이디:sa, 비밀번호 : password, db : member)
            string connectionString = "server = 127.0.0.1; uid = sa; pwd = password; database = member;";
            // Sql 새연결정보 생성
            MySqlConnection sqlConn = new MySqlConnection(connectionString);
            MySqlCommand sqlComm = new MySqlCommand();
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = "insert into tbl_member (id,name,addr) values ('abc','홍길동','서울');";
            //sqlComm.CommandText = "update tbl_member set addr='서울' where id='abc' and name='홍길동';";
            //sqlComm.CommandText = "delete tbl_member where id='abc' and name='홍길동' and addr='서울';";
            sqlConn.Open();
            sqlComm.ExecuteNonQuery();
            sqlConn.Close();
        }
    }
}


select
using MySql.Data.MySqlClient;
using System;

namespace MySql
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "server = 127.0.0.1,3535; uid = sa; pwd = password; database = member;";
            // Sql 새연결정보 생성
            MySqlConnection sqlConn = new MySqlConnection(connectionString);
            MySqlCommand sqlComm = new MySqlCommand();
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = "select id,addr from tbl_member where name='홍길동' order by id asc limit 10";
            sqlConn.Open();
            using (MySqlDataReader SqlRs = sqlComm.ExecuteReader())
            {
                Console.WriteLine("ID \t \t | Address");
                while (SqlRs.Read())
                {
                    Console.WriteLine(string.Format("{0} \t \t | {1}", SqlRs[0].ToString(), SqlRs[1].ToString()));
                }
            }
            sqlConn.Close();
        }
    }
}

댓글 없음:

댓글 쓰기