繁体   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