提问人:Pradeep 提问时间:10/17/2023 最后编辑:Pradeep 更新时间:10/18/2023 访问量:41
在MySQL中,如何比较同一行中的五个值,并得到同一行中特定列的输出?
in MySQL, how to compare five values in the same row and get the output of a particular column in the same row?
问:
在MySQL表中,我有四行六列,不包括主键。列名是 值 1、值 2、值 3、值 4、值 5 和输出。用户输入表单 WinForms 应用 对于值为 1 到 5 的列。例如,值 1 = A、值 2 = B、值 3 = C、值 4 = D、值 5 = E 和输出 = Goods。现在,我想比较所有五个值 A = B = C = D = E,然后得到输出值 Goods 并显示给用户。
string connection = "server = localhost; user id = root; database =
sample; password = 12345678";
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand cmd;
try
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO result(value 1, value 2,
value 3, value 4, value 5) VALUES (@value 1, @value 2, @value 3,
@value 4, @value 5)";
cmd.Parameters.Add("@value 1", MySqlDbType.VarChar).Value =
value1textbox.Text;
cmd.Parameters.Add("@value 2", MySqlDbType.VarChar).Value
= value2textbox.Text;
cmd.Parameters.Add("@value 3", MySqlDbType.VarChar).Value
= value3textbox.Text;
cmd.Parameters.Add("@value 4", MySqlDbType.VarChar).Value
= value4textbox.Text;
cmd.Parameters.Add("@value 5", MySqlDbType.VarChar).Value
= value5textbox.Text;
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Saved Successfully");
}
else
{
MessageBox.Show("Error");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
con.Close();
}
现在,值已成功添加,但我不知道如何比较相同的行值并获得相同行输出列的输出。
感谢您对!!!的帮助
答:
0赞
User12345
10/18/2023
#1
你可以试试这个:
string connection = "server = localhost; user id = root; database =
sample; password = 12345678";
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand cmd;
try
{
con.Open();
// Create a SQL command to retrieve the output based on input values
cmd = con.CreateCommand();
cmd.CommandText = "SELECT output FROM constellation " +
"WHERE value1 = @value1 AND value2 = @value2 " +
"AND value3 = @value3 AND value4 = @value4 AND value5 = @value5";
cmd.Parameters.Add("@value1", MySqlDbType.VarChar).Value = input1TextBox.Text;
cmd.Parameters.Add("@value2", MySqlDbType.VarChar).Value = input2TextBox.Text;
cmd.Parameters.Add("@value3", MySqlDbType.VarChar).Value = input3TextBox.Text;
cmd.Parameters.Add("@value4", MySqlDbType.VarChar).Value = input4TextBox.Text;
cmd.Parameters.Add("@value5", MySqlDbType.VarChar).Value = input5TextBox.Text;
// Execute the query
object result = cmd.ExecuteScalar();
if (result != null)
{
outputTextBox.Text = result.ToString();
}
else
{
outputTextBox.Text = "No matching data found.";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
我只是将命令文本从您的代码更改为(因为我们那里只有 1 个输出值)。如果 value 不是唯一的,您可以添加 and 只得到 TOP 1。ExecuteNonQuery
ExecuteScalar
order by
LIMIT 1
评论