ASP.NET MVC与Sql Server建立连接

 

用惯了使用Entity Framework连接数据库,本篇就来体验使用SqlConnection连接数据库。


打开Sql Server 2008,创建数据库,创建如下表:

 

 
 
create table Product
(
    Id int identity(1,1) not null primary key,
    Name nvarchar(50) null,
    quantity nvarchar(50) null,
    Price nvarchar(50) null
    
)
go

 

点击Visual Studio中"工具"菜单下的"连接到数据库",选择"Microsoft SQL Server"作为数据源。

1

 

点击"继续"。

 

连接刚创建的数据库,点击"确定"。

2

 

打开"服务器资源管理器",如下:

3

 

右键"服务器资源管理器",点击"属性",复制连接字符串。并粘帖到Web.config中的connectionStrings节点下。

 

 
 
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=PC201312021114;Initial Catalog=MVC;User ID=sa;Password=密码"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

 

现在,需要一个处理连接的帮助类,如下:

 

 
 
  public class SqlDB
    {
        protected SqlConnection conn;
 
 
        //打开连接
        public bool OpenConnection()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            try
            {
                bool result = true;
                if (conn.State.ToString() != "Open")
                {
                    conn.Open();
                }
                return result;
            }
            catch (SqlException ex)
            {
                return false;
            }
        }
 
 
        //关闭连接
        public bool CloseConnection()
        {
            try
            {
                conn.Close();
                return true;
            }
            catch (Exception ex)
            {
 
 
                return false;
            }
        }
    }
 
 
 
 

 

创建TestController如下:

 

 
 
   public class TestController : Controller
    {
 
 
        private SqlDB _db = new SqlDB();
        //
        // GET: /Test/
        public ActionResult Index()
        {
            bool r = _db.OpenConnection();
            if (r)
            {
                return Content("连接成功");
            }
            else
            {
                return Content("连接失败");
            }
        }
    }
 
 
 
 

 

浏览Test/Index视图页,显示连接成功。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值