程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c#銜接mdf文件示例分享

c#銜接mdf文件示例分享

編輯:C#入門知識

c#銜接mdf文件示例分享。本站提示廣大學習愛好者:(c#銜接mdf文件示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是c#銜接mdf文件示例分享正文


C#銜接當地.mdf文件:項目中右鍵點擊,新增——數據——基於辦事的數據庫,項面前目今直接生成.mdf數據庫文件,後台(數據庫的寫入用參數傳遞):


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace ADO.NET
{
    class Program
    {
        static void Main(string[] args)
        {
            //SQLServer 附加mdf文件
            string dataDir = AppDomain.CurrentDomain.BaseDirectory;
            if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\"))
            {
                dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
                AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
            }
            using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
            {
                conn.Open();
                //寫入一條數據
                string strUserName = "功課本";
                string strPWD = "Ab123456";

                using (SqlCommand sqlCmd = conn.CreateCommand())
                {
                    sqlCmd.CommandText = "insert into Mytable1(Name,Password) values (@UserName,@PWD) ";//銜接字符串停止參數化
                    SqlParameter[] sqlPara = new SqlParameter[] {
                    new SqlParameter("UserName",strUserName),
                    new SqlParameter("PWD",strPWD)
                    };
                    sqlCmd.Parameters.AddRange(sqlPara); //把Paramerter 數組參數添加到sqlCmd中
                    sqlCmd.ExecuteNonQuery();
                    Console.WriteLine("Insert OK");
                }

                //從表中讀取數據
                string strRead = "SELECT   ID, Name, Password FROM      MyTable1 ";
                using (SqlCommand sqlCmd = new SqlCommand(strRead, conn))
                {
                    //sqlDataReader 逐行讀取數據
                    using (SqlDataReader sdr = sqlCmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {

                            int id = sdr.GetInt32(sdr.GetOrdinal("ID"));  //sdr.GetOrdinal 獲得列的序號
                            string Name = sdr.GetString(sdr.GetOrdinal("Name"));
                            bool PWD = sdr.IsDBNull(sdr.GetOrdinal("Password"));
                            Console.WriteLine("ID:{0},Name:{1},PWD:{2}", id, Name, PWD);
                            Console.WriteLine(sdr.GetString(1));
                        }
                    }
                }
                conn.Close();//此處可以省略,Dispose()辦法會主動檢討
            }
        }
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved