大家好我试图获取用户名和ID,现在我只是获取id。
这是存储过程:
ALTER PROCEDURE [dbo].[spLogin]
@username VARCHAR(MAX),
@password VARCHAR(MAX)
AS
SELECT [dbo].[User].[Id],[dbo].[User].[Username] FROM [dbo].[User]
WHERE username=@username AND password=@password
这是我的方法:
public class UserBL
{
string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
public int CheckUserLogin(UserL User)
{
using (SqlConnection con = new SqlConnection(conexion))
{
SqlCommand comObj = new SqlCommand("spLogin", con);
comObj.CommandType = CommandType.StoredProcedure;
comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
comObj.Parameters.Add(new SqlParameter("@password", User.Password));
con.Open();
return Convert.ToInt32(comObj.ExecuteScalar());
}
}
}
这是我的用户类:
public class UserL
{
public int UserID { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
我正在检查用户是否已退出id使用Ajax,但我需要创建会话,为了做到这一点,我需要
答案 0 :(得分:2)
using (SqlConnection con = new SqlConnection(conexion))
{
SqlCommand comObj = new SqlCommand("spLogin", con);
comObj.CommandType = CommandType.StoredProcedure;
comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
comObj.Parameters.Add(new SqlParameter("@password", User.Password));
con.Open();
var dr = comObj.ExecuteReader();
while(dr.Read())
{
var userId = dr["Id"];
var username = dr["Username"];
// do something with your data....
}
con.Close();
}
你可以也使用输出参数。 Google it:https://www.google.no/search?q=stored+procedures+output+parameters&oq=stored+procedures+output+parameters
您将密码作为明文放在数据库中。 不要这样做。请阅读我关于Codeproject的文章:https://www.codeproject.com/Articles/425150/Beginners-guide-to-a-secure-way-of-storing-passwor
答案 1 :(得分:1)
使用executereader,因为执行标量返回单个值。
public class UserBL
{
string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
public int CheckUserLogin(UserL User)
{
using (SqlConnection con = new SqlConnection(conexion))
{
SqlCommand comObj = new SqlCommand("spLogin", con);
comObj.CommandType = CommandType.StoredProcedure;
comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
comObj.Parameters.Add(new SqlParameter("@password", User.Password));
con.Open();
var dr=comObj.ExecuteScalar();
while(dr.read())
{
int userid=convert.toint16(dr[0]);
string Password=dr[1].tostring();
// now Manipulate as per as your requirment
}
}
}
}
答案 2 :(得分:1)
您可以使用.env
返回Dictionary
和UserName
,使Id
成为关键点,Id
为值。
UserName