簡體   English   中英

C#ASP.NET從同一mysql命令中選擇多個列,並在后面的代碼中使用它們

[英]C# ASP.NET Selecting multiple column from same mysql command and use them in code behind

我會做這件事:

"select nome,cognome from Utenti where CodiceCliente = @codice"

然后在后面的代碼中使用“ nome”中的值和“ cognome”中的值。 與PHP有關聯數組,在C#ASP.NET中?
到目前為止,我一直使用兩個不同的命令,但是現在很煩人。
例:

MySqlCommand getNome = new MySqlCommand("select Nome from Utenti where CodiceCliente = @codice", userConnection);
    MySqlCommand getCognome = new MySqlCommand("select Cognome from Utenti where CodiceCliente = @codice", userConnection);
    MySqlCommand getEmail = new MySqlCommand("select IndirizzoEmail from Utenti where CodiceCliente = @codice", userConnection);
    getNome.Parameters.AddWithValue("@codice", codice);
    getCognome.Parameters.AddWithValue("@codice", codice);
    getEmail.Parameters.AddWithValue("@codice", codice);
    userConnection.Open();
    string nome = Convert.ToString(getNome.ExecuteScalar());
    string cognome = Convert.ToString(getCognome.ExecuteScalar());
    string email = Convert.ToString(getEmail.ExecuteScalar());

你能幫助我嗎?
以前謝謝
丹尼爾

簡單用法:

using(var connection = new MySqlConnection(myConnString))
{
   var cmd = connection.CreateCommand();
   cmd.CommandText = "select nome,cognome from Utenti where CodiceCliente = @codice";
   cmd.Parameters.AddWithValue("@codice", value);
   var reader = cmd.ExecuteReader();
   while(reader.Read())
   {
       // here could be problems if database value is null
       var nome = reader["nome"];
       var cognome = reader["cognome"];
   }
}

您可以嘗試以下方法:

using(var connection = new MySqlConnection(myConnString))
{
   var cmd = connection.CreateCommand();
   cmd.CommandText = "select nome,cognome from Utenti where CodiceCliente = @codice";
   cmd.Parameters.AddWithValue("@codice", value);
   var reader = cmd.ExecuteReader();
  if(reader.HasRows) {
   while(reader.Read())
   {

       var nome = reader[0];
       var cognome = reader[1];
   }
reader.Close();
}
}

您必須檢查DataReader是否有行以避免異常,最后不要忘記關閉它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM