-2

The query below returns a single VARCHAR value and I want to return this value as a string. How would I do that?

Code snippet:

string query = "SELECT " + FieldName + " FROM " + Table4 + " WHERE StartTime=" +
                    StartTime + " AND SystemId=" + SystemId + '"';
string result = "";

MySqlCommand cmd = new MySqlCommand(query, connection);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
        result = ...  // set "result" to the output of the query here
}
return result;
}
Community
  • 1
  • 1
burntchowmein
  • 474
  • 1
  • 4
  • 16
  • Searching for "C# mysql tutorial" will provide links to resources giving examples and explaining how to use the created [MySqlDataReader](https://dev.mysql.com/doc/dev/connector-net/8.0/html/T_MySql_Data_MySqlClient_MySqlDataReader.htm) which implements [DbDataReader](https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbdatareader?view=netframework-4.8) (it will also show how to write 'safe[r]' SQL). If there is a _specific_ issue other than "enter code here", it'd be better to call it out. – user2864740 Jun 03 '20 at 20:19
  • 1
    In this particular case [ExecuteScalar](https://dev.mysql.com/doc/dev/connector-net/8.0/html/M_MySql_Data_MySqlClient_MySqlCommand_ExecuteScalar.htm) might also be worth looking into. – user2864740 Jun 03 '20 at 20:23
  • 1
    this code is **vulnerable to sql injection** use prepared statements with parameters see https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html – nbk Jun 03 '20 at 20:59

2 Answers2

1

You can create a List and add the values to the list. After return the List.

BennoDual
  • 5,865
  • 15
  • 67
  • 153
0

How to return a VARCHAR query result as a string:

while (reader.Read())
{
        results= reader.GetString(0);                          // Added this
}
return results;
burntchowmein
  • 474
  • 1
  • 4
  • 16
  • After you fix the syntax errors, that returns a random `FieldName` You need to learn how to [use parameters](https://stackoverflow.com/questions/7505808/) before someone calls your statement with a FieldName of `0; DELETE`. – Dour High Arch Jun 05 '20 at 21:54