Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve more than one column using ExecuteScalar?

Tags:

c#

I am getting 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, e.g.:

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

I need each column in a string:

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

But that is not possible. How is this achieved?

like image 487
Rooney Avatar asked Jun 09 '11 10:06

Rooney


People also ask

What is use of ExecuteScalar () method?

ExecuteScalar: Use this operation to execute any arbitrary SQL statements in SQL Server to return a single value. This operation returns the value only in the first column of the first row in the result set returned by the SQL statement.

What does ExecuteScalar return?

ExecuteScalar Method. Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.

What does ExecuteScalar return if no rows?

If the row does not exist, the result of command. ExecuteScalar() is null, which is then casted to a null string and assigned to getusername .

Does ExecuteScalar close connection?

No, you need to explicitly open and close the connection when using ExecuteScalar(). Save this answer.


2 Answers

ExecuteScalar executes 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.

To achecive this you need to use SqlCommand.ExecuteReader Method

like image 132
PSK Avatar answered Nov 09 '22 10:11

PSK


ExecuteScalar returns first columns of 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];
like image 36
DeveloperX Avatar answered Nov 09 '22 09:11

DeveloperX