当前位置: 动力学知识库 > 问答 > 编程问答 >

c# compare input to mysql value

问题描述:

I wanted to create a function on which a user can guess the value from a MySQL database. label2 is randomly generated by other codes, so the user will have to guess the partner value of the label2 by inputting texbox1. I try to use the usual login function for the code

 s = "SELECT val2 FROM data_reader.db WHERE val1='" + this.label2.Text + "'and image='" + this.textBox1.Text + "';";

int count = 0;

while (mdr.Read())

{

count = count + 1;

}

if (count == 1)

{

MessageBox.Show("correct");

}

else

{

MessageBox.Show("wrong");

}

problem with this code is it always return wrong even when the value are correct. is there any missing algorithm or maybe my code is not suitable for this purpose?

网友答案:

You forgot insert a space character between the label2.Text value and the AND junction.

s = "SELECT val2 FROM data_reader.db WHERE val1='" + this.label2.Text 
    + "' AND image='" + this.textBox1.Text + "';";
网友答案:

Ok i'll help you with something else here

First: Lesson i learned here, never use " + ", you should use AddWithValue on the query parameters, something like this:

cmd.CommandText = "SELECT val2 FROM data_reader.db WHERE val1 = @value1 and [email protected]";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@value1", this.label2.Text);
cmd.Parameters.AddWithValue("@image", this.textBox1.Text);

It is easier to understand and more secure.

Second: You just need to use

if (mdr.Read())
{
    MessageBox.Show("Correct!");
}
else
{
    MessageBox.Show("Wrong!");
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: