How can I get SQL result into a STRING variable?

Viewed 83559

I'm trying to get the SQL result in a C# string variable or string array. Is it possible? Do I need to use SqlDataReader in some way? I'm very new to C# functions and all, used to work in PHP, so please give a working example if you can (If relevant I can already connect and access the database, insert and select.. I just don't know how to store the result in a string variable).

5 Answers

Try this:

public string SaveStringSQL(string pQuery, string ConnectionString)
{
    var connection = new Conexao(ConnectionString);
    connection.Open();

    SqlCommand command = new SqlCommand(pQuery, connection.Connection);
    var SavedString = (string)command.ExecuteScalar();

    connection.Close();

    return SavedString;
}

The ExecuteScalar function saves whatever type of data there is on your database - you just have to specify it.

Keep in mind that it can only save one line at a time.

Related