Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Asp.net WEB窗体中要在标签中显示的MySqlCommand_C#_Mysql_Asp.net_Webforms - Fatal编程技术网

C# Asp.net WEB窗体中要在标签中显示的MySqlCommand

C# Asp.net WEB窗体中要在标签中显示的MySqlCommand,c#,mysql,asp.net,webforms,C#,Mysql,Asp.net,Webforms,我有这个sql命令 string myreg = "select registration_no from truck where truck_id ='" + truckID + "'"; MySqlCommand cmd = new MySqlCommand(myreg, conn); 我想将myreg的值放入我的RegistrationNo.Text标签 我有这个注册号Text=myreg并在我的页面上显示select registration\u no from

我有这个sql命令

string myreg = "select registration_no from truck where truck_id ='" + truckID + "'";
            MySqlCommand cmd = new MySqlCommand(myreg, conn);
我想将
myreg
的值放入我的
RegistrationNo.Text
标签


我有这个
注册号Text=myreg
并在我的页面上显示select registration\u no from truck where truck\u id

您需要阅读有关其工作原理及其提供程序的信息。
要在文本框中获取该查询的结果,您需要

  • 打开到MySql服务器的连接
  • 准备要发送到服务器的命令
  • 得到结果
  • 将结果写入文本框
所有这些段落都需要使用特定的类和一些代码来将所有内容粘合在一起

 // Prepare your command using a parameter placeholder
 string myreg = "select registration_no from truck where truck_id =@id";

 // Build the connection to the server and build the command to execute
 using (MySqlConnection cnn = new MySqlConnection(.... the connection string that identifies your server and db ))
 using (MySqlCommand cmd = new MySqlCommand(myreg, cnn))
 {
      // Open the connection
      cnn.Open();

      // Add the parameter expected 
      cmd.Parameters.Add("@id", MySqlDbType.VarChar).Value = truckID;

      // Execute the command and get back the return value (if found)
      object result = cmd.ExecuteScalar();

      // Check if the ExecuteScalar has returned something
      if(result != null)
           RegistrationNo.Text = result.ToString();
      else
           ... message to your user about the failed search ...
 }
另外,我假设您的变量truckID是一个字符串,因为在原始代码中,您在单引号之间传递了它,但如果它是一个整数,则需要将参数类型修改为MySqlDbType.Int32
此外,我使用了该方法,而不是因为我认为您的查询只返回一行和一列,对于此任务,最好使用ExecuteScalar,也可以使用datareader。请参见此处

using (connection)
{
    SqlCommand command = new SqlCommand(
     "SQL Query",
      connection);
    connection.Open();

    SqlDataReader reader = command.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
            Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                reader.GetString(1));
        }
    }
    else
    {
        Console.WriteLine("No rows found.");
    }
    reader.Close();
}