ASP.NET MVC与Sql Server建立连接
2015-07-06 17:10
681 查看
用惯了使用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"作为数据源。点击"继续"。连接刚创建的数据库,点击"确定"。打开"服务器资源管理器",如下:右键"服务器资源管理器",点击"属性",复制连接字符串。并粘帖到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视图页,显示连接成功。
相关文章推荐
- 【回味无穷】ASP.NET内部控件
- ASP.NET动态添加用户控件的方法
- Asp.net Vnext IValueProvider
- 关于在asp.net中的调试
- aspx 体现mvc 模式的增删改查
- 解密aspx与aspx.cs的关系
- ASP.Net核心对象之context.Server对象几个常用方法
- Web服务器和ASP.Net
- asp了解
- 第1章 ASP.NET4.0开发技术概述
- Picture Aspect Ratio
- ASP.NET 为什么要有 MVC
- ASP.NET分页
- asp.net webapi 多文件上传
- 大型高性能ASP.NET系统架构设计
- ABP(现代ASP.NET样板开发框架)主题线下交流会(上海)开始报名了!
- Asp.Net传值
- ASP.NET动态添加用户控件的方法
- 蛋疼的替换(纯粹是为了vim而vim)
- AspectJ 出现错误::0 can't find referenced pointcut 的解决