[英]C# get sql table column value and put it in a variable
I have a user login menu.我有一个用户登录菜单。 I want to redirect the user based on their Level.
我想根据用户的级别重定向用户。 The Level data is in the SQL table.
级别数据在 SQL 表中。 I want to get the Level data from the table based on their username and assign it to a variable.
我想根据他们的用户名从表中获取级别数据并将其分配给一个变量。
protected void btnDefault_Click(object sender, EventArgs e)
{
//filter entered text
string strUserName = Tools.checkSQLInjection(txtUserName.Text).Trim();
string strPassword = Tools.checkSQLInjection(txtPassword.Text);
string strError = "";
//Get Dealer Level Value
SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email='" + strUserName + "'");
string strDealerLvl = "dealerLvl".ToString();
int intDealerLvl;
bool isParsable = Int32.TryParse(strDealerLvl, out intDealerLvl);
if (strDealerLvl == "1")
{ Response.Redirect("/dealers/dashboard"); }
else if (strDealerLvl == "2")
{ Response.Redirect("/dealers/dashboard-2"); }
using(SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email= @strUserName", connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@strUserName", strUserName);
DataSet ds = new DataSet();
using(SqlDataAdapter da = new SqlDataAdapter(command))
da.Fill(ds);
//Get the result of the first row
DataRow dr = ds.Tables[0].Rows[0];
//Get the value of the column in the first row
string strDealerLvl = dr["dealerLvl"].ToString();
}
You don't seem to be checking the password, but perhaps that supposed to come later.您似乎没有检查密码,但也许应该稍后再检查。
A working code stub to do this would look like say this:执行此操作的工作代码存根看起来像这样说:
DataTable MyTable = new DataTable();
int intDealerLvl = 0;
using (SqlCommand cmdSQL = new SqlCommand("SELECT dealerLv1 FROM Users where email = @meail",
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("@email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
}
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
switch (intDealerLvl)
{
case 1:
{
Response.Redirect("/dealers/dashboard");
break;
}
case 2:
{
Response.Redirect("/dealers/dashboard-2");
break;
}
default:
{
// no level found - where to go??
break;
}
}
However, it not clear if you supposed to be checking the password, and if so then of course we use this:但是,不清楚您是否应该检查密码,如果是这样,那么我们当然会使用它:
DataTable MyTable = new DataTable();
string strSQL;
strSQL = "SELECT dealerLv1 FROM Users where email = @Email and Password = @Pass";
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("@email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Parameters.Add("@Pass", SqlDbType.NVarChar).Value = strPassword;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.