Summary of three methods for connecting. net MVC to the local database,. netmvc
. Net MVC connection data local database three methods
<appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="con" value="server=.\sqlexpress; user id = sa;password = a123456;database = xsgl1;max pool size=512;"/> </appSettings> <connectionStrings> <add name="conSql" connectionString="server=(local)\sqlexpress; User Id = sa;password = a123456;database = xsgl1;max pool size=512;"/> </connectionStrings> Configuration
Public class HomeController: Controller {// GET:/Home/public ActionResult Index () {# region connect SQL function one SqlConnectionStringBuilder one = new SqlConnectionStringBuilder (); one. dataSource = "(local) \ sqlexpress"; one. initialCatalog = "xsgl1"; one. userID = "sa"; one. password = "a123456"; one. maxPoolSize = 512; SqlConnection sct = new SqlConnection (one. connectionString); # endregion # region connect SQL function two // string conn = ConfigurationManager. appSettings ["con"]. toString (); // SqlConnection sct = new SqlConnection (conn); # endregion # region connect SQL function three // string conn = ConfigurationManager. connectionStrings ["conSql"]. connectionString; // SqlConnection sct = new SqlConnection (conn); # endregion SqlCommand scm = new SqlCommand (); scm. connection = sct; scm. commandType = CommandType. text; scm. commandText = "select Course name from kc where course No. = 'a001'"; sct. open (); SqlDataReader sdr = scm. executeReader (); if (sdr. read () {ViewBag. hao = sdr ["Course name"];} sdr. close (); return View () ;}public ActionResult About () {return View () ;}} Controller
@{ ViewBag.Title = "Index"; } @ViewBag.hao