Sqlcommand. executescalar Method

Source: Internet
Author: User
Sqlcommand. executescalar Method

Returns the first column of the First row in the returned result set. Ignore other columns or rows.

Namespace:System. Data. sqlclient
Assembly:System. Data (in system. Data. dll
Medium)

Syntax

C #

public override Object ExecuteScalar ()
 

Return Value

The first column or empty reference of the first row in the result set (if the result set is empty ).

Exception

Exception type Condition

Sqlexception

An exception occurred while executing the command on the locked line. If Microsoft. NET Framework 1.0 is used, this exception is not generated.

Remarks

UseExecutescalarMethod to retrieve a single value (for example, an aggregate value) from the database ). And use executereader
Method, and then use sqldatareader
Compared to the operations required to generate a single value for the returned data, this operation requires less code.

TypicalExecutescalarThe Query format is similar to the following C # example:


Copy code
 cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";Int32 count = (Int32) cmd.ExecuteScalar();
Example

The following example creates a sqlcommand and then uses
Executescalar
Run it. Two strings are passed to this example. One String indicates the new value to be inserted into the table, and the other string is used to connect to the data source. If a new row has been inserted, this function returns a new"Identity"Column value. If it fails, return
0.

C # 

Copy code
static public int AddProductCategory(string newName, string connString){Int32 newProdID = 0;string sql ="INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "+ "SELECT CAST(scope_identity() AS int)";using (SqlConnection conn = new SqlConnection(connString)){SqlCommand cmd = new SqlCommand(sql, conn);cmd.Parameters.Add("@Name", SqlDbType.VarChar);cmd.Parameters["@name"].Value = newName;try{conn.Open();newProdID = (Int32)cmd.ExecuteScalar();}catch (Exception ex){Console.WriteLine(ex.Message);}}return (int)newProdID;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.