.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             #endregion
17 17             #region connect sql function two
18 18             //string conn = ConfigurationManager.AppSettings["con"].ToString();
19 19             //SqlConnection sct = new SqlConnection(conn);
20 20             #endregion
21 21             #region connect sql function three
22 22             //string conn = ConfigurationManager.ConnectionStrings["conSql"].ConnectionString;
23 23             //SqlConnection sct = new SqlConnection(conn);
24 24             #endregion
25 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.hao
5 5 <h2>Index</h2>
View

转载于:https://www.cnblogs.com/jinzhaoyoujiu/p/mvc_sql_server.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值