C# MSSQL

      在〈C# MSSQL〉中尚無留言

建立連線

string strConn= "server=localhost;database=資料庫;uid=帳號;pwd=密碼;MultipleActiveResultSets=true";
 SqlConnection conn = new SqlConnection(strConn);
 conn.Open();

建立命令物件

string strCmd="select * from table"
SqlCommand cmd = new SqlCommand(strCmd, conn);
cmd.Parameters.AddWithValue("@value1", area);
cmd.Parameters.AddWithValue("@value2", dateStart);
cmd.Parameters.AddWithValue("@value3", dateEnd);

執行命令

SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()){
    list.Add(getItem(dr));
}
dr.Close();
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        public const String dbConnection = "server=mahaljsp.asuscomm.com;database=巨匠資料庫;uid=pcschool;pwd=123456;MultipleActiveResultSets=true";
        public static SqlConnection conn = new SqlConnection(dbConnection);
        static void Main(string[] args)
        {
            conn.Open();
            Console.WriteLine("連線成功");
            //Add();
            //Show();
            //Delete();
            Update();
        }
        static void Add()
        {
            string str = "insert into 學員資料表 (name, tel, address) values (@v1, @v2, @v3)";
            SqlCommand cmd = new SqlCommand(str, conn);
            cmd.Parameters.AddWithValue("@v1","吳明學");
            cmd.Parameters.AddWithValue("@v2", "0987987987");
            cmd.Parameters.AddWithValue("@v3", "彰化市");
            cmd.ExecuteNonQuery();
        }
        static void Show()
        {
            string str = "select * from 學員資料表 order by id";
            SqlCommand cmd=new SqlCommand(str, conn);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    Console.Write(dr[i]+" ");
                }
                Console.WriteLine();
            }

        }
        static void Delete()
        {
            string str = "delete 學員資料表 where id=28";
            SqlCommand cmd = new SqlCommand(str, conn);
            cmd.ExecuteNonQuery();
            Show();
        }
        static void Update()
        {
            string str = "update 學員資料表 set address=@v1 where id = @v2";
            SqlCommand cmd = new SqlCommand(str, conn);
            cmd.Parameters.AddWithValue("@v1", "彰化市石頭路一段");
            cmd.Parameters.AddWithValue("@v2", 1);
            cmd.ExecuteNonQuery();
            Show();
        }
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *