简体   繁体   中英

Select with where clause in MySql

Is it possible to select data from a table with a specific ID? I know it works for update but what is the code for the select ?

Im using c# in visual studios, my goal is to display the details in readOnly textboxes .

 string corp = 
   @"select corporateName, 
            corporateAddress, 
            corporateContact 
       from corporatemembership 
      where corporateID = CorpID.Text";

this should do it

string Command = 
  @"select corporateName, 
           corporateAddress, 
           corporateContact 
      from corporatemembership 
     where corporateID = @CorpID;";

using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
    using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
    {
        myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("@CorpID", CorpID.Text));
        DataTable dtResult = new DataTable();
        myDataAdapter.Fill(dtResult);
        corporateName.Text = dtResult.Rows[0]["corporateName"];
        corporateAddress.Text = dtResult.Rows[0]["corporateAddress"];
        corporateContact.Text = dtResult.Rows[0]["corporateContact"];
    }
}

probably you should add some error handling and handle the case that CorpID doesn't exist

UPDATE another approach

string Command =
        @"select corporateName, 
                 corporateAddress, 
                 corporateContact 
            from corporatemembership 
            where corporateID = @CorpID;";
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
    mConnection.Open();
    using (MySqlCommand cmd = new MySqlCommand(Command, mConnection))
    {
        cmd.Parameters.Add(new MySqlParameter("@CorpID", CorpID.Text));
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                corporateName.Text = (string)reader["corporateName"];
                corporateAddress.Text = (string)reader["corporateAddress"];
                corporateContact.Text = (string)reader["corporateContact"];
            }
        }
    }
}

Yes, it is possible, your sql string is OK, except last part, you will edit last part

string corp = "select corporateName, corporateAddress, corporateContact from corporatemembership where corporateID = " + "'" + CorpID.Text + "'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM