欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net MVC 连接数据本地数据库三种方法总结

程序员文章站 2023-11-14 14:05:52
.net mvc 连接数据本地数据库三种方法

.net mvc 连接数据本地数据库三种方法

  <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 课程名 from kc where 课程号='a001'";
       sct.open();
       sqldatareader sdr = scm.executereader();
       if (sdr.read())
       {
        viewbag.hao = sdr["课程名"];
      }
      sdr.close();
      return view();
    }
    public actionresult about()
    {
      return view();
     }
   }

controller
@{
  viewbag.title = "index";
 }
 @viewbag.hao
 <h2>index</h2>