Share via

My SQl Query Error

Mohamed Rafi N 106 Reputation points
2022-03-22T11:53:44.977+00:00

I have stored userid and password in mysql database, this query is showing login successfully for not stored data, so please correct it

string query = "select * from login where userid=@userid and password=@Lee ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Parameters.AddWithValue("@userid", id);
cmd.Parameters.AddWithValue("@Lee ", password);
cmd.Connection = cnn;
cnn.Open();
cmd.ExecuteNonQuery();
DialogResult dr = MessageBox.Show("Are you sure to Login now?", "Confirmation Message", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
MessageBox.Show("Login Successfully");
cnn.Close();
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

Developer technologies | ASP.NET Core | Other
0 comments No comments

Answer accepted by question author

Yijing Sun-MSFT 7,106 Reputation points
2022-03-23T02:56:10.107+00:00

Hi @Mohamed Rafi N ,
I think your userid and password are unique. So I suggest you could count the same userid and the password. If the count is more than 1, you could login in.

       string strSql = "SELECT COUNT(*) from login where userid=@userid and password=@password";  
      cmd.Connection = cnn;  
      cnn.Open();  
        int count = Convert.ToInt32(command.ExecuteScalar());  
        if (count >= 1)  
            MessageBox.Show("Login Successfully");  
        else  
             MessageBox.Show("Please register");  

Best regards,
Yijing Sun


If the answer is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,606 Reputation points Volunteer Moderator
    2022-03-22T18:32:49.717+00:00

    You need to use ExecuteReader rather than ExecuteNonQuery.

    var results = cmd.ExecuteReader();

    Then check results e.g. results.HasRows which returns true if a record was found, false otherwise.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.