这是我的用户登录代码。我想将用户输入与SQL匹配。其中emp_ID,密码和用户类型(Admin,employee)应等于用户输入。此代码无法正常运行。因此,当我选择用户类型时,它表示拒绝访问
try
{
myconnection.Open();
cmd = new SqlCommand("select * from loging where emp_ID = '" + username.Text + "' and password = '" + password.Text + "' and user_type = '"+label4.Text+"'", myconnection);
myreader = cmd.ExecuteReader();
int count = 0;
while (myreader.Read())
{
count = count + 1;
}
if (count == 1 || comboBox1.Text == label4.Text )
{
MessageBox.Show("Access Granted");
}
else if (count > 1)
{
MessageBox.Show("Access denied");
}
else
{
MessageBox.Show("Access denied");
}
myconnection.Close();
}
答案 0 :(得分:0)
虽然你还没有解释你所面临的确切问题,但我想建议你一些基本的东西来提供更多的安全性。
建议1:您的SELECT
查询对SQL-Injection
次攻击开放,因此我建议您使用Parameterised queries
来避免它们。
建议2:如果您只想count
SELECT
次查询返回的行总数,则可以使用以下查询来简化任务:
SELECT COUNT(*) FROM TableName;
上面的查询将返回返回的总行数。
建议3:在您的代码中,您不需要有两个其他块,因为两者都相似。因此,您可以删除其中一个以提高代码的可读性。
注意:正如我已经在评论中提到的那样,如果您可以告诉我们您的代码中Combobox1
究竟是什么以及它与label4
的关系,那么它会有所帮助我们来解决您的问题。
完整代码:
try
{
myconnection.Open();
cmd = new SqlCommand("select count(*) from loging where emp_ID =@emp_ID and password =@password and user_type = @user_type", myconnection);
cmd.Parameters.AddWithValue("@emp_ID",username);
cmd.Parameters.AddWithValue("@password",password);
cmd.Parameters.AddWithValue("@user_type",label4.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count == 1 || comboBox1.Text == label4.Text )
{
MessageBox.Show("Access Granted");
}
else
{
MessageBox.Show("Access denied");
}
myconnection.Close();
}
答案 1 :(得分:0)
一些关于安全的建议:
也许应该给出2-3个其他建议,但我的眼睛已经流血......