在asp.net中的mvc控制器中使用sql [英] using sql in mvc controller in asp.net

查看:60
本文介绍了在asp.net中的mvc控制器中使用sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




i想在visual studio 2012中使用sql,对于exp:in homecontroller.cs



或make sqlclass将在调用默认页面时全局调用..



im使用MVC。



如何这样做

解决方案

希望它有所帮助:



  public  ActionResult Index()
{
string connectionString = 数据源= Whatever;初始目录= Northwind;集成安全性= True;;
// 你的普通sql
string commandText = 选择 +
_c.CompanyName +
来自Customers _c +
内连接订单_o on _o.CustomerID = _c.CustomerID +
其中_o.ShipCity = @city;
List< string> result = new List< string>();
使用(SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(commandText,connection);
cmd.Parameters.Add( @ city,SqlDbType.NVarChar);
cmd.Parameters [ @ city]。值= 马德里;

connection.Open();
使用(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader.GetString( 0 ));
}
}
}

return 查看(结果);
}
< / string > < / string > ;


1.创建连接字符串&all。

2.创建操作结果

3.Route或map path使用Action结果查看


参考



使用SQL Server和实体框架设计ASP.NET MVC应用程序的初学者指南 [ ^ ]

Hi
i want to use sql in visual studio 2012 , for exp : in homecontroller.cs

or make sqlclass which will be called globally when default page is called..

i m using MVC .

how to do this

解决方案

Hope it helps:

public ActionResult Index()
        {
        	string connectionString = "Data Source=Whatever; Initial Catalog=Northwind; Integrated security=True;";
			// your "normal" sql here
			string commandText = "select" +
									" _c.CompanyName" +
								" from Customers _c" +
								" inner join Orders _o on _o.CustomerID = _c.CustomerID" +
								" Where _o.ShipCity = @city";
			List<string> result = new List<string>();
			using (SqlConnection connection = new SqlConnection(connectionString))
			{
				SqlCommand cmd = new SqlCommand(commandText, connection);
				cmd.Parameters.Add("@city", SqlDbType.NVarChar);
				cmd.Parameters["@city"].Value = "Madrid";

				connection.Open();
				using (SqlDataReader reader = cmd.ExecuteReader())
				{
					while (reader.Read())
					{
						result.Add(reader.GetString(0));
					}
				}
			}

        	return View(result);
        }
</string></string>


1.create connection string & all.
2.Create Action Result
3.Route or map path View with Action result


Refer

Beginner's Guide for Designing ASP.NET MVC Applications using SQL Server and Entity Framework[^]


这篇关于在asp.net中的mvc控制器中使用sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆