16. 7. 28.

C#으로 MS-SQL 연동

insert,update,delete
using System;
using System.Data.SqlClient;

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


select
using System;
using System.Data.SqlClient;

namespace MsSql
{
    class Program
    {
        
        static void Main(string[] args)
        {
            // Sql 연결정보(서버:127.0.0.1, 포트:3535, 아이디:sa, 비밀번호 : password, db : member)
            string connectionString = "server = 127.0.0.1,3535; uid = sa; pwd = password; database = member;";
            // Sql 새연결정보 생성
            SqlConnection sqlConn = new SqlConnection(connectionString);
            SqlCommand sqlComm = new SqlCommand();
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = "select top 10 id,addr from tbl_member where name=@param1 order by id asc";
            sqlComm.Parameters.AddWithValue("@param1", "김준");
            sqlConn.Open();
            using (SqlDataReader 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();
        }
    }
}

댓글 없음:

댓글 쓰기