c# - 使用 SqlDataReader 使条件正确?
问题描述
var a = "1";
var b = "2";
var c = "3";
var name = authResult.ExtraData["email"];
string connectionString = null;
SqlConnection cnn;
SqlCommand cmd;
string sql = null;
SqlDataReader reader;
connectionString = "Data Source = dj0043\\sqlexpress; Initial Catalog = XXXX; Integrated Security = True";
sql = "Select EmployeeRoles.RoleId From EmployeeList Inner Join EmployeeRoles on EmployeeList.EmployeeId = EmployeeRoles.EmployeeId Where EmailId = name";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
if (reader == a)
{
return Redirect(Url.Action("Employee", "Home"));
}
else if (sql == b)
{
return Redirect(Url.Action("Index", "Home"));
}
else if (sql == c)
{
return Redirect(Url.Action("Index", "Home"));
}
}
reader.Close();
cmd.Dispose();
cnn.Close();
}
在这种情况下,如果任何用户具有 1 id 将被重定向到该页面,反之亦然。
谁能告诉我如何在SqlDataReader
这种情况下工作?
解决方案
首先,您的 SQL 查询不正确。您应该将@name
参数发送到查询中。
我更喜欢这样做,因为它更清洁
var a = "1";
var b = "2";
var c = "3";
var name = authResult.ExtraData["email"];
var connectionString = "Data Source = dj0043\\sqlexpress; Initial Catalog = XXXX; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "Select EmployeeRoles.RoleId From EmployeeList Inner Join EmployeeRoles on EmployeeList.EmployeeId = EmployeeRoles.EmployeeId Where EmailId = @name";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader["RoleId"].ToString() == a)
{
return Redirect(Url.Action("Employee", "Home"));
}
else if (reader["RoleId"].ToString() == b)
{
return Redirect(Url.Action("Index", "Home"));
}
else if (reader["RoleId"].ToString() == c)
{
return Redirect(Url.Action("Index", "Home"));
}
}
}
}
}
推荐阅读
- sql - 每年犯罪率排名前 N 的城市
- reactjs - 禁用 Next.JS 文件系统路由的特定路径
- javascript - 如何使用相同的js函数处理多个文件上传 - jquery
- php - 在控制器中为 Model::create 之外的模型实例赋值
- node.js - 当滚动条不活动时,您能帮我将弹出详细信息更改为 div tabindex = "0" -1 吗?
- websocket - Chrome 和 Safari 可以从同一页面访问两个不同的端口吗?
- c# - XDocument 提取具有相同元素但不同属性的 XML 数据
- mongoose - 开玩笑,用lean() 模拟猫鼬模型
- javascript - 有人可以告诉我如何删除或隐藏此 JavaScript 代码吗?
- python - 只想在python中打印电话号码而不是其他