.net MVC 连接数据本地数据库三种方法总结
.netMVC连接数据本地数据库三种方法
<appSettings> <addkey="webpages:Version"value="2.0.0.0"/> <addkey="webpages:Enabled"value="false"/> <addkey="PreserveLoginUrl"value="true"/> <addkey="ClientValidationEnabled"value="true"/> <addkey="UnobtrusiveJavaScriptEnabled"value="true"/> <addkey="con"value="server=.\sqlexpress;userid=sa;password=a123456;database=xsgl1;maxpoolsize=512;"/> </appSettings> <connectionStrings> <addname="conSql"connectionString="server=(local)\sqlexpress;UserId=sa;password=a123456;database=xsgl1;maxpoolsize=512;"/> </connectionStrings> Configuration
publicclassHomeController:Controller { // //GET:/Home/ publicActionResultIndex() { #regionconnectsqlfunctionone SqlConnectionStringBuilderone=newSqlConnectionStringBuilder(); one.DataSource="(local)\\sqlexpress"; one.InitialCatalog="xsgl1"; one.UserID="sa"; one.Password="a123456"; one.MaxPoolSize=512; SqlConnectionsct=newSqlConnection(one.ConnectionString); #endregion #regionconnectsqlfunctiontwo //stringconn=ConfigurationManager.AppSettings["con"].ToString(); //SqlConnectionsct=newSqlConnection(conn); #endregion #regionconnectsqlfunctionthree //stringconn=ConfigurationManager.ConnectionStrings["conSql"].ConnectionString; //SqlConnectionsct=newSqlConnection(conn); #endregion SqlCommandscm=newSqlCommand(); scm.Connection=sct; scm.CommandType=CommandType.Text; scm.CommandText="select课程名fromkcwhere课程号='A001'"; sct.Open(); SqlDataReadersdr=scm.ExecuteReader(); if(sdr.Read()) { ViewBag.hao=sdr["课程名"]; } sdr.Close(); returnView(); } publicActionResultAbout() { returnView(); } } Controller
@{ ViewBag.Title="Index"; } @ViewBag.hao <h2>Index</h2>