在MySql中选择where子句

时间:2015-08-04 12:19:03

标签: c# mysql select visual-studio-2013 where

是否可以从具有特定ID的表中选择数据?我知道它适用于更新但是选择的代码是什么?

我在视觉工作室使用c#,我的目标是在readOnly文本框中显示细节

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

2 个答案:

答案 0 :(得分:3)

这应该做到

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"];
    }
}

可能你应该添加一些错误处理并处理CorpID不存在的情况

更新为德米特里提供另一种方法

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"];
            }
        }
    }
}

答案 1 :(得分:0)

是的,有可能, 你的sql字符串没问题,除了最后一部分,你将编辑最后一部分

string corp ="从corporatemembership中选择corporateName,corporateAddress,corporateContact,其中corporateID =" +"'" + CorpID.Text +"'";