你的位置:首页 > ASP.net教程

[ASP.net教程].net MVC 连接数据本地数据库三种方法


 1 1  <appSettings> 2 2   <add key="webpages:Version" value="2.0.0.0" /> 3 3   <add key="webpages:Enabled" value="false" /> 4 4   <add key="PreserveLoginUrl" value="true" /> 5 5   <add key="ClientValidationEnabled" value="true" /> 6 6   <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 7 7   <add key="con" value="server=.\sqlexpress; user id = sa;password = a123456;database = xsgl1;max pool size=512;"/> 8 8  </appSettings> 9 9  <connectionStrings>10 10   <add name="conSql" connectionString="server=(local)\sqlexpress; User Id = sa;password = a123456;database = xsgl1;max pool size=512;"/>11 11  </connectionStrings> 

Configuration
 1 1   public class HomeController : Controller 2 2   { 3 3     // 4 4     // GET: /Home/ 5 5  6 6     public ActionResult Index() 7 7     { 8 8       #region connect sql function one 9 9       SqlConnectionStringBuilder one = new SqlConnectionStringBuilder();10 10       one.DataSource = "(local)\\sqlexpress";11 11       one.InitialCatalog = "xsgl1";12 12       one.UserID = "sa";13 13       one.Password = "a123456";14 14       one.MaxPoolSize = 512;15 15       SqlConnection sct = new SqlConnection(one.ConnectionString);16 16       #endregion17 17       #region connect sql function two18 18       //string conn = ConfigurationManager.AppSettings["con"].ToString();19 19       //SqlConnection sct = new SqlConnection(conn);20 20       #endregion21 21       #region connect sql function three22 22       //string conn = ConfigurationManager.ConnectionStrings["conSql"].ConnectionString;23 23       //SqlConnection sct = new SqlConnection(conn);24 24       #endregion25 25       SqlCommand scm = new SqlCommand();26 26       scm.Connection = sct;27 27       scm.CommandType = CommandType.Text;28 28       scm.CommandText = "select 课程名 from kc where 课程号='A001'";29 29       sct.Open();30 30       SqlDataReader sdr = scm.ExecuteReader();31 31       if (sdr.Read())32 32       {33 33         ViewBag.hao = sdr["课程名"];34 34       }35 35       sdr.Close();36 36       return View();37 37     }38 38     public ActionResult About()39 39     {40 40       return View();41 41     }42 42   }

Controller
1 1 @{2 2   ViewBag.Title = "Index";3 3 }4 4 @ViewBag.hao5 5 <h2>Index</h2>

View