標籤:
用慣了使用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建立串連