我有一个名为Logins
的数据库表,其中有3列:Username
,Password
和Category
。类别有两种类型:Admin
和User
。
我有一个带有两个文本框的表单,用户将在其中写下他的用户名和密码。使用用户名文本框输入,我想检查给定的用户名是Admin
还是User
,并根据该用户名打开不同的表单。
我收到以下错误:
意外错误:
"'"
附近的语法不正确
SqlConnection con = new SqlConnection("Data Source=JAYI-PC\\SQLEXPRESS;Initial Catalog=db-ub;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand(@"SELECT Count(*) FROM Logins
WHERE Username=@uname and
Password=@pass,Category=@ctgy", con);
cmd.Parameters.AddWithValue("@uname", textBox_usern.Text);
cmd.Parameters.AddWithValue("@pass", textBox_pwd.Text);
cmd.Parameters.AddWithValue("@ctgy", c); //Can't understand how to check it
int result = (int)cmd.ExecuteScalar();
if (result > 0)
{
if (c== "Admin")//this one will chek whether user is admin or user
{
MessageBox.Show("Welcome Admin");
Admin f1 = new Admin();
f1.Show();
}
else
{
MessageBox.Show("Welcome " + textBox_usern.Text);
FormCheck f3 = new FormCheck();
f3.Show();
}
}
else
{
MessageBox.Show("Incorrect login");
}
textBox_usern.Clear();
textBox_pwd.Clear();
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error:" + ex.Message);
}
答案 0 :(得分:3)
您的查询不正确,错过了一个and
并且有额外的,
。它应该是这样的
SELECT Count(*) FROM Logins
WHERE Username=@uname and
Password=@pass and Category=@ctgy
答案 1 :(得分:2)
我相信您正在尝试阅读类别更改您的查询
SqlCommand cmd = new SqlCommand(@"SELECT Category FROM Logins
WHERE Username=@uname and
Password=@pass", con);
cmd.Parameters.AddWithValue("@uname", textBox_usern.Text);
cmd.Parameters.AddWithValue("@pass", textBox_pwd.Text);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
var c = reader["Category"].ToString();
if (c== "Admin")//this one will chek whether user is admin or user
{
MessageBox.Show("Welcome Admin");
Admin f1 = new Admin();
f1.Show();
}
else
{
MessageBox.Show("Welcome " + textBox_usern.Text);
FormCheck f3 = new FormCheck();
f3.Show();
}
}
else
{
MessageBox.Show("Incorrect login");
}
textBox_usern.Clear();
textBox_pwd.Clear();
答案 2 :(得分:1)
你的程序只检查用户是否存在..不会发回类别。所以你应该使用执行阅读器。如果找到用户,将返回详细信息。检查以下代码。
SqlConnection con = new SqlConnection("Data Source=JAYI-PC\\SQLEXPRESS;
Initial Catalog=db-ub;Integrated Security=True");
try
{
con.Open();
string cat = null;
SqlCommand cmd = new SqlCommand(@"SELECT Username,Password,Category
FROM Logins WHERE Username=@uname and
Password=@pass", con);
cmd.Parameters.AddWithValue("@uname", textBox_usern.Text);
cmd.Parameters.AddWithValue("@pass", textBox_pwd.Text);
SqlDataReader rdr = cmd.ExecuteReader();
//int result = (int)cmd.ExecuteScalar();
int result = 0;
while(rdr.Read()
{
result++; //to confirm it entered while loop so data is there
cat = rdr["Category"].ToString();
}
if (result > 0)
{
if (cat == "Admin")//this one will chek whether user is admin or
user
{
MessageBox.Show("Welcome Admin");
Admin f1 = new Admin();
f1.Show();
}
else
{
MessageBox.Show("Welcome " + textBox_usern.Text);
FormCheck f3 = new FormCheck();
f3.Show();
}
}
else
{
MessageBox.Show("Incorrect login");
}
textBox_usern.Clear();
textBox_pwd.Clear();