Npgsql.NpgsqlCommand.ExecuteScalar Method
Executes a query against the Npgsql.NpgsqlConnection and expects a single value as output

Syntax

public object ExecuteScalar ()

Returns

a object containing the output value.

Remarks

This command returns a single value as the output of the command execution.

C# Example

using System;
using System.Data;
using Npgsql;

public class NpgsqlExecuteScalar
{
	public static void Main(String[] args)
	{
		NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
		conn.Open();
		
		NpgsqlCommand command = new NpgsqlCommand("select version()", conn);
		String serverversion;
		
		try
		{
			serverversion = (String)command.ExecuteScalar();
			Console.WriteLine("PostgreSQL server version: {0}", serverversion);
		}
		finally
		{
			conn.Close();
		}
	}
}
		

Compiling and executing the above code gives the output

PostgreSQL server version: PostgreSQL 7.3.2 on i386-redhat-linux-gnu, compiled by GCC i386-redhat-linux-gcc (GCC) 3.2.2 20030213 (Red Hat Linux 8.0 3.2.2-1)

If a query is executed that returns more than one column and/or more than one row, only the first column in the first row is returned. For example, tweaking the above example to make it

Example

using System;
using System.Data;
using Npgsql;

public class NpgsqlExecuteScalar
{
	public static void Main(String[] args)
	{
		NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
		conn.Open();
		
		NpgsqlCommand command = new NpgsqlCommand("select version(), upper('foo')", conn);
		String serverversion;
		
		try
		{
			serverversion = (String)command.ExecuteScalar();
			Console.WriteLine("PostgreSQL server version: {0}", serverversion);
		}
		finally
		{
			conn.Close();
		}
	}
}
		
still prints

PostgreSQL server version: PostgreSQL 7.3.2 on i386-redhat-linux-gnu, compiled by GCC i386-redhat-linux-gcc (GCC) 3.2.2 20030213 (Red Hat Linux 8.0 3.2.2-1)

Note that the exact output in the above will vary depending on the exact version of the database.

Requirements

Namespace: Npgsql
Assembly: Npgsql (in Npgsql.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0