ASP.NET MVC與Sql Server建立串連

來源:互聯網
上載者:User

標籤:

 

用慣了使用Entity Framework串連資料庫,本篇就來體驗使用SqlConnection串連資料庫。


開啟Sql Server 2008,建立資料庫,建立如下表:

 

create table Product
(
    Id int identity(1,1) not null primary key,
    Name nvarchar(50) null,
    quantity nvarchar(50) null,
    Price nvarchar(50) null
    
)
go

 

點擊Visual Studio中"工具"菜單下的"串連到資料庫",選擇"Microsoft SQL Server"作為資料來源。

 

點擊"繼續"。

 

串連剛建立的資料庫,點擊"確定"。

 

開啟"伺服器總管",如下:

 

右鍵"伺服器總管",點擊"屬性",複製連接字串。並粘帖到Web.config中的connectionStrings節點下。

 

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=PC201312021114;Initial Catalog=MVC;User ID=sa;Password=密碼"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

 

現在,需要一個處理串連的協助類,如下:

 

  public class SqlDB
    {
        protected SqlConnection conn;
        //開啟串連
        public bool OpenConnection()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            try
            {
                bool result = true;
                if (conn.State.ToString() != "Open")
                {
                    conn.Open();
                }
                return result;
            }
            catch (SqlException ex)
            {
                return false;
            }
        }
        //關閉串連
        public bool CloseConnection()
        {
            try
            {
                conn.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }

 

建立TestController如下:

 

   public class TestController : Controller
    {
        private SqlDB _db = new SqlDB();
        //
        // GET: /Test/
        public ActionResult Index()
        {
            bool r = _db.OpenConnection();
            if (r)
            {
                return Content("串連成功");
            }
            else
            {
                return Content("串連失敗");
            }
        }
    }

 

瀏覽Test/Index視圖頁,顯示串連成功。

ASP.NET MVC與Sql Server建立串連

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.