简体   繁体   English

C#-MySQL-如果状态为“ a”,则从列获取值

[英]C# - MySQL - Get value from column if status is 'a'

I'm trying to get a value from 123 if the status is a / This is what my table looks like 我想从一个值123 ,如果statusa /这是我的表看起来像

|123|status|
|dsg|a     |
|ert|b     |
|abc|a     |

So, I only want to get dsg and abc , because there status is a . 所以,我只是想获得dsgabc ,因为有statusa

But how can I do this in C#? 但是如何在C#中做到这一点?

This is my current code: 这是我当前的代码:

public string getAll() {
    command6 = new MySqlCommand("SELECT 123 FROM table1 WHERE status= ?status", connection);
    command6.Prepare();

    command6.Parameters.AddWithValue("?status", "a");
    command6.ExecuteNonQuery();


    return command6.ExecuteScalar().ToString();
}

But this only returns dsg , not dsg and abc :( 但这只会返回dsg ,而不会返回dsgabc :(

  • Bram 布拉姆

You get only one value because you're using ExecuteScalar() method which is used to return one value only (in your case the value of the first record returned). 您仅获得一个值,因为您正在使用ExecuteScalar()方法,该方法仅用于返回一个值(在您的情况下,返回的第一条记录的值)。

You need to use a reader to return multiple values: 您需要使用阅读器来返回多个值:

 MySqlDataReader reader = command6.ExecuteReader();
 while(reader.Read())
 {
     String value = reader.GetString(0); // do something with it, e.g. put into a list
 }

You need to also change the output type of your function getAll() to return multiple string values (eg an array or list) or concatenate all the values from the database into one string. 您还需要更改函数getAll()的输出类型,以返回多个字符串值(例如,数组或列表)或将数据库中的所有值连接为一个字符串。

You are using ExecuteScalar which return only first record and ignore others as msdn say: 您正在使用ExecuteScalar,它仅返回第一条记录,而忽略其他记录,如msdn所说:

ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. ExecuteScalar执行查询,并返回查询返回的结果集中第一行的第一列。 Additional columns or rows are ignored. 其他列或行将被忽略。

You need to use: 您需要使用:

MySqlDataReader dr = command6.ExecuteReader();
List<string> data=new List<string>();
while (dr.Read())
{
    data.Add(dr["123"].ToString());        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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