ASP.NET MVC與Sql Server建立連接


 

用慣了使用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"作為數據源。

1

 

點擊"繼續"。

 

連接剛創建的數據庫,點擊"確定"。

2

 

打開"服務器資源管理器",如下:

3

 

右鍵"服務器資源管理器",點擊"屬性",復制連接字符串。並粘帖到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視圖頁,顯示連接成功。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM