How to get more than one column using ExecuteScalar?

I get one column using ExecuteScalar:

 cmd.commandtext = "select rodeuser from customer_db_map";
    string rodecustomer = cmd.executescalar;

But I need to get more than one column, for example:

 cmd.commandtext = "select rodeuser,username,password from customer_db_map";

I need every column in a row:

 string rodecustomer = cmd.ExecuteScalar();
 string username= cmd.ExecuteScalar();
 string password = cmd.ExecuteScalar();

But this is unreal. How is this achieved?

+3
source share
3 answers

ExecuteScalarexecutes the query and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

For this you need to use SqlCommand.ExecuteReaderMethod

+7
source

ExecuteScalar returns the first columns of the first row, so you can use a trick like this

var m = cmd.commandtext =    select str(rodeuser)+','+username+','+password  from 
    (select rodeuser,username,password from customer_db_map)

string[] result=m.ToString().Split(new char[] { ',' });
string rodeuser=result[0];

string username=result[1];

string password=result[2];
+1
source

Unable to retrieve multiple values ​​using ExecuteScalar. Instead, you would like to use ExecuteReader .

Here is an example:

Extracting data using DataReader (ADO.NET)

Alternatively, you can use the DataAdapter :

Populating a Dataset from a DataAdapter (ADO.NET)

0
source

All Articles