System.Data.Common.DbCommand.ExecuteScalar()

Here are the examples of the csharp api class System.Data.Common.DbCommand.ExecuteScalar() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

121 Examples 7

1. Example

Project: CodeSnippets
Source File: Transactions.cs
public static string CurrentIsolationLevel(this DbContext context)
        {
            using (DbCommand command = context.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = CurrentIsolationLevelSql;
                command.Transaction = context.Database.CurrentTransaction.GetDbTransaction();
                return (string)command.ExecuteScalar();
            }
        }

2. Example

Project: linq2db
Source File: RetryingDbCommand.cs
public override object ExecuteScalar()
		{
			return _policy.Execute(() => _command.ExecuteScalar());
		}

3. Example

Project: ALinq
Source File: AccessDbConnection.cs
public override object ExecuteScalar()
        {
            return source.ExecuteScalar();
        }

4. Example

Project: ALinq
Source File: Connection.cs
public override object ExecuteScalar()
        {
            return source.ExecuteScalar();
        }

5. Example

Project: referencesource
Source File: DBCommand.cs
public virtual Task<object> ExecuteScalarAsync(CancellationToken cancellationToken) {
            if (cancellationToken.IsCancellationRequested) {
                return ADP.CreatedTaskWithCancellation<object>();
            }
            else {
                CancellationTokenRegistration registration = new CancellationTokenRegistration();
                if (cancellationToken.CanBeCanceled) {
                    registration = cancellationToken.Register(CancelIgnoreFailure);
                }

                try {
                    return Task.FromResult<object>(ExecuteScalar());
                }
                catch (Exception e) {
                    registration.Dispose();
                    return ADP.CreatedTaskWithException<object>(e);
                }
            }
        }

6. Example

Project: effort
Source File: DbCommandWrapper.cs
public override object ExecuteScalar()
        {
            return this.wrappedCommand.ExecuteScalar();
        }

7. Example

Project: EDDiscovery
Source File: SQLiteConnectionED.cs
public bool keyExistsCN(string sKey)
        {
            using (DbCommand cmd = CreateCommand("select ID from Register WHERE ID=@key"))
            {
                cmd.AddParameterWithValue("@key", sKey);
                return cmd.ExecuteScalar() != null;
            }
        }

8. Example

Project: EDDiscovery
Source File: SQLiteConnectionED.cs
public string GetSettingStringCN(string key, string defaultvalue)
        {
            try
            {
                using (DbCommand cmd = CreateCommand("SELECT ValueString from Register WHERE ID = @ID"))
                {
                    cmd.AddParameterWithValue("@ID", key);
                    object ob = cmd.ExecuteScalar();

                    if (ob == null || ob == DBNull.Value)
                        return defaultvalue;

                    string val = (string)ob;

                    return val;
                }
            }
            catch
            {
                return defaultvalue;
            }
        }

9. Example

Project: EDDiscovery
Source File: SQLiteDBClass.cs
static public object SQLScalar(SQLiteConnectionED cn, DbCommand cmd)      
        {
            object ret = null;

            try
            {
                ret = cmd.ExecuteScalar();
                return ret;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("SqlNonQuery Exception: " + ex.Message);
                throw;
            }
        }

10. Example

Project: EDDiscovery
Source File: SystemClassEDSM.cs
public static void CheckSystemAliases()
        {
            using (SQLiteConnectionSystem cn = new SQLiteConnectionSystem())
            {
                // Check that the SystemAliases table is not empty
                using (DbCommand cmd = cn.CreateCommand("SELECT COUNT(id) FROM SystemAliases"))
                {
                    long nrows = (long)cmd.ExecuteScalar();

                    if (nrows == 0)
                    {
                        //Console.WriteLine("Populating system aliases table");
                        RemoveHiddenSystems();
                    }
                }
            }
        }

11. Example

Project: Glimpse
Source File: GlimpseDbCommand.cs
public override object ExecuteScalar()
        {
            object result;
            var commandId = Guid.NewGuid();

            var timer = this.LogCommandSeed();
            this.LogCommandStart(commandId, timer);  
            try
            {
                result = InnerCommand.ExecuteScalar();
            }
            catch (Exception exception)
            {
                this.LogCommandError(commandId, timer, exception, "ExecuteScalar");
                throw;
            }

            this.LogCommandEnd(commandId, timer, null, "ExecuteScalar");

            return result;
        }

12. Example

Project: Dos.ORM
Source File: Database.cs
private object DoExecuteScalar(DbCommand command)
        {

            WriteLog(command);

            return command.ExecuteScalar();

        }

13. Example

Project: Dos.ORM
Source File: Database.cs
private object DoExecuteScalar(DbCommand command)
        {

            WriteLog(command);

            return command.ExecuteScalar();

        }

14. Example

Project: Dos.ORM
Source File: Database.cs
private object DoExecuteScalar(DbCommand command)
        {

            WriteLog(command);

            return command.ExecuteScalar();

        }

15. Example

Project: Craig-s-Utility-Library
Source File: DbCommandExtensions.cs
public static DataType ExecuteScalar<DataType>(this DbCommand Command, DataType Default = default(DataType))
        {
            if (Command == null)
                return Default;
            Command.Open();
            return Command.ExecuteScalar().To<object, DataType>(Default);
        }

16. Example

Project: Craig-s-Utility-Library
Source File: DbCommandExtensions.cs
public static DataType ExecuteScalar<DataType>(this DbCommand Command, DataType Default = default(DataType))
        {
            if (Command == null)
                return Default;
            Command.Open();
            return Command.ExecuteScalar().To<object, DataType>(Default);
        }

17. Example

Project: PlayoutAutomation
Source File: DbSchema.cs
public static bool Update(this DbConnection connection)
        {
            DbCommand command = connection.CreateCommand();
            command.CommandText = "SELECT `value` FROM params WHERE `section`=\"DATABASE\" AND `key`=\"VERSION\";";
            object version = command.ExecuteScalar();
            return true;
        }

18. Example

Project: dotnetmigrations
Source File: RollbackCommand.cs
private long GetPreviousDatabaseVersion(long currentVersion)
        {
            // note that we have to use 'IN' instead of '=' for the subquery
            // becuase sql server compact doesn't support subqueries that return scalar values
            string cmdText = string.Format("SELECT [version] FROM [schema_migrations] WHERE [id] IN (SELECT MAX([id]) FROM [schema_migrations] WHERE [version] <> {0})",
                                           currentVersion);

            long previousVersion;

            using (DbCommand cmd = Database.CreateCommand())
            {
                cmd.CommandText = cmdText;
                previousVersion = cmd.ExecuteScalar<long>(-1);
            }

            return previousVersion;
        }

19. Example

Project: dotnetmigrations
Source File: DatabaseCommandBase.cs
protected long GetDatabaseVersion()
        {
            // note that we have to use 'IN' instead of '=' for the subquery
            // becuase sql server compact doesn't support subqueries that return scalar values
            const string command = "SELECT [version] FROM [schema_migrations] WHERE [id] IN (SELECT MAX([id]) FROM [schema_migrations])";

            long currentVersion = -1;

            try
            {
                using (DbCommand cmd = Database.CreateCommand())
                {
                    cmd.CommandText = command;
                    var version = cmd.ExecuteScalar<string>();
                    if (version != null)
                    {
                        version = version.Trim();
                    }
                    long.TryParse(version, out currentVersion);

                    if (currentVersion < 0)
                    {
                        throw new SchemaException("schema_migrations table appears to be corrupted");
                    }
                }
            }
            catch (DbException ex)
            {
                Log.WriteError(ex.Message);
            }

            return currentVersion;
        }

20. Example

Project: dotnetmigrations
Source File: DbCommandExtensions.cs
public static T ExecuteScalar<T>(this DbCommand cmd, T defaultValue)
        {
            var obj = cmd.ExecuteScalar();
            if (obj == null || obj == DBNull.Value)
            {
                return defaultValue;
            }
            return (T)Convert.ChangeType(obj, typeof (T));            
        }

21. Example

Project: Restful
Source File: SessionProvider.cs
public virtual T ExecuteScalar<T>( CommandBuilder builder )
        {
            using( DbCommand command = this.CreateSqlCommand( builder ) )
            {
                return command.ExecuteScalar().Cast<T>();
            }
        }

22. Example

Project: sqlhelper2
Source File: CommandDatabase.cs
public T ExecuteScalar<T>(string sql, object parameters) {
            PrepareCommand(sql, parameters);

            return (T) Command.ExecuteScalar();
        }

23. Example

Project: nuodb-dotnet
Source File: LINQUnitTest.cs
[TestFixtureSetUp]
        public static void Init() 
        {
            Utils.CreateHockeyTable();
            using (NuoDbConnection connection = new NuoDbConnection(TestFixture1.connectionString))
            {
                DbCommand command = new NuoDbCommand("select count(*) from hockey", connection);

                connection.Open();
                tableRows = Utils.ToInt(command.ExecuteScalar());
            }
        }

24. Example

Project: SmartStoreNET
Source File: CachingCommand.cs
public override object ExecuteScalar()
		{
			if (!IsCacheable)
			{
				return _command.ExecuteScalar();
			}

			var key = CreateKey();

			object value;

			if (_cacheTransactionInterceptor.GetItem(Transaction, key, out value))
			{
				return value;
			}

			value = _command.ExecuteScalar();

			// TODO: somehow determine expiration
			TimeSpan? duration = null;

			_cacheTransactionInterceptor.PutItem(
				Transaction,
				key,
				value,
				_commandTreeFacts.AffectedEntitySets.Select(s => s.Name),
				duration);

			return value;
		}

25. Example

Project: Cheezburger-BDSM
Source File: Importer.cs
private object ExecuteScalar(string commandText, params object[] args)
        {
            object result;
            try
            {
                using (DbCommand command = CreateCommand(commandText, args))
                    result = command.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw new Exception("Error in command: " + commandText, ex);
            }
            if (result is DBNull)
                return null;
            return result;
        }

26. Example

Project: DotNetSiemensPLCToolBoxLibrary
Source File: MsSQLStorage.cs
public Int64 ReadCount(DatasetConfig datasetConfig)
        {
            try
            {
                CheckAndEstablishReadConnection();

                readCmd.Connection = readDBConn;
                readCmd.CommandText = "SELECT COUNT(*) FROM " + datasetConfig.Name;

                return Convert.ToInt64(readCmd.ExecuteScalar());
            }
            catch (Exception ex)
            { }
            return 0;
        }

27. Example

Project: DotNetSiemensPLCToolBoxLibrary
Source File: MySQLStorage.cs
public Int64 ReadCount(DatasetConfig datasetConfig)
        {
            try
            {
                CheckAndEstablishReadConnection();

                readCmd.Connection = readDBConn;
                readCmd.CommandText = "SELECT COUNT(*) FROM " + datasetConfig.Name;

                return Convert.ToInt64(readCmd.ExecuteScalar());
            }
            catch (Exception ex)
            { }
            return 0;
        }

28. Example

Project: DotNetSiemensPLCToolBoxLibrary
Source File: PostgreSQLStorage.cs
public Int64 ReadCount(DatasetConfig datasetConfig)
        {
            try
            {
                CheckAndEstablishReadConnection();

                readCmd.Connection = readDBConn;
                readCmd.CommandText = "SELECT COUNT(*) FROM " + datasetConfig.Name;

                return Convert.ToInt64(readCmd.ExecuteScalar());
            }
            catch (Exception ex)
            { }
            return 0;
        }

29. Example

Project: DotNetSiemensPLCToolBoxLibrary
Source File: SQLLiteStorage.cs
public Int64 ReadCount(DatasetConfig datasetConfig)
        {
            try
            {
                CheckAndEstablishReadConnection();

                readCmd.Connection = readDBConn;
                readCmd.CommandText = "SELECT COUNT(*) FROM " + datasetConfig.Name;

                return Convert.ToInt64(readCmd.ExecuteScalar());
            }
            catch (Exception ex)
            { }
            return 0;
        }

30. Example

Project: EDDiscovery
Source File: SQLiteConnectionED.cs
public int GetSettingIntCN(string key, int defaultvalue)
        {
            try
            {
                using (DbCommand cmd = CreateCommand("SELECT ValueInt from Register WHERE ID = @ID"))
                {
                    cmd.AddParameterWithValue("@ID", key);

                    object ob = cmd.ExecuteScalar();

                    if (ob == null || ob == DBNull.Value)
                        return defaultvalue;

                    int val = Convert.ToInt32(ob);

                    return val;
                }
            }
            catch
            {
                return defaultvalue;
            }
        }

31. Example

Project: EDDiscovery
Source File: SQLiteConnectionED.cs
public double GetSettingDoubleCN(string key, double defaultvalue)
        {
            try
            {
                using (DbCommand cmd = CreateCommand("SELECT ValueDouble from Register WHERE ID = @ID"))
                {
                    cmd.AddParameterWithValue("@ID", key);

                    object ob = cmd.ExecuteScalar();

                    if (ob == null || ob == DBNull.Value)
                        return defaultvalue;

                    double val = Convert.ToDouble(ob);

                    return val;
                }
            }
            catch
            {
                return defaultvalue;
            }
        }

32. Example

Project: EDDiscovery
Source File: SqLiteDBSchema.cs
private static void UpdateSchema()
        {
            bool id_edsm_isset = false;
            usi/n ..... /n //View Source file for more details /n }

33. Example

Project: RiotControl
Source File: DatabaseCommand.cs
public object ExecuteScalar()
		{
			Start();
			object output = Command.ExecuteScalar();
			Stop();
			return output;
		}

34. Example

Project: RawDataAccessBencher
Source File: Massive.cs
public virtual object Scalar(string sql, params object[] args)
        {
            object result = null;
            using (var conn = OpenConnection())
            {
                result = CreateCommand(sql, conn, args).ExecuteScalar();
            }
            return result;
        }

35. Example

Project: RawDataAccessBencher
Source File: Massive.cs
public virtual object Scalar(string sql, params object[] args)
		{
			object result = null;
			using(var conn = OpenConnection())
			{
				result = CreateCommand(sql, conn, args).ExecuteScalar();
			}
			return result;
		}

36. Example

Project: simple-1c
Source File: AbstractSqlDatabase.cs
protected TResult ExecuteScalar<TResult>(string commandText, params object[] args)
        {
            return ExecuteWithResult(commandText, args,
                c => (TResult) Convert.ChangeType(c.ExecuteScalar(), typeof(TResult)));
        }

37. Example

Project: ReliableDbProvider
Source File: Massive.cs
public virtual object Scalar(string sql, params object[] args)
        {
            object result = null;
            using (var conn = OpenConnection())
            {
                result = CreateCommand(sql, conn, args).ExecuteScalar();
            }
            return result;
        }

38. Example

Project: NServiceKit.OrmLite
Source File: Massive.cs
public virtual object Scalar(string sql, params object[] args)
        {
            object result = null;
            using (var conn = OpenConnection())
            {
                result = CreateCommand(sql, conn, args).ExecuteScalar();
            }
            return result;
        }

39. Example

Project: nuodb-dotnet
Source File: Utils.cs
internal static int GetTableRows()
        {
            using (NuoDbConnection connection = new NuoDbConnection(connectionString))
            {
                DbCommand command = new NuoDbCommand("select count(*) from hockey", connection);

                connection.Open();
                return Utils.ToInt(command.ExecuteScalar());
            }
        }

40. Example

Project: nuodb-dotnet
Source File: TestFixture.cs
private static void VerifyBulkLoad(int expectedCount, string expectedFirstRow)
        {
            using (NuoDbConnection connection = new NuoDbConnection(connectionString))
            {
                connection.Open();

                DbCommand command = new NuoDbCommand("select count(*) from temp", connection);
                object val = command.ExecuteScalar();

                Assert.AreEqual(expectedCount, Utils.ToInt(val));

                command = new NuoDbCommand("select col from temp", connection);
                val = command.ExecuteScalar();

                Assert.AreEqual(expectedFirstRow, val);
            }
        }

41. Example

Project: Ilaro.Admin
Source File: Massive.cs
public virtual object Scalar(string sql, params object[] args)
        {
            object result = null;
            using (var conn = OpenConnection())
            {
                result = CreateCommand(sql, conn, args).ExecuteScalar();
            }
            return result;
        }

42. Example

Project: spring-net
Source File: CommandCallbackDao.cs
public virtual int FindCountWithPostalCodeWithDelegate(string postalCode)
        {
            // Using anonymous delegates allows you to easily reference the
            // surrounding parameters for use with the DbCommand processing.

            return AdoTemplate.Execute<int>(delegate(DbCommand command)
                   {
                       // Do whatever you like with the DbCommand... downcast to get 
                       // provider specific funtionality if necesary.
                                                    
                       command.CommandText = cmdText;
                         
                       DbParameter p = command.CreateParameter();
                       p.ParameterName = "@PostalCode";
                       p.Value = postalCode;
                       command.Parameters.Add(p);

                       return (int)command.ExecuteScalar();

                   });

        }

43. Example

Project: spring-net
Source File: CommandCallbackDao.cs
public T DoInCommand(DbCommand command)
            {
                T resultObject = new T();
                DbParameter p = command.CreateParameter();
                p.ParameterName = "@PostalCode";
                p.Value = postalCode;
                command.Parameters.Add(p);
                
                resultObject.count = (int)command.ExecuteScalar();
                return resultObject;
            }

44. Example

Project: spring-net
Source File: GenericAdoTemplateTests.cs
[Test]
        public void CommandDelegateUsageDownCast()
        {
            string name = "Jack";
			int count = adoTemplate.Execute<int>((DbCommand command) =>
                                                     {
                                                         SqlCommand sqlCommand = command as SqlCommand;
                                                         command.CommandText =
                                                             "select count(*) from TestObjects where Name = @Name";

                                                         sqlCommand.Parameters.AddWithValue("@Name", name);

                                                         return (int) command.ExecuteScalar();
                                                     });
            Assert.AreEqual(1, count);
        }

45. Example

Project: SummerBatch
Source File: DbOperator.cs
public T Query<T>(ParsedQuery query, IQueryParameterSource parameterSource = null)
        {
            using (var command = GetCommand(query.SubstitutedQuery))
            {
                SetParameters(command, query, parameterSource);
                return Converter.Convert<T>(command.ExecuteScalar());
            }
        }

46. Example

Project: DNTProfiler
Source File: ProfiledDbCommand.cs
public override object ExecuteScalar()
        {
            object result = null;
            var context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, null);
            _profiler.ScalarExecuting(InternalCommand, context);
            _stopwatch.Restart();
            try
            {
                result = InternalCommand.ExecuteScalar();
            }
            catch (Exception e)
            {
                context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, e);
                _profiler.ScalarExecuting(InternalCommand, context);
                throw;
            }
            finally
            {
                _stopwatch.Stop();
                context = NHProfilerContextProvider.GetLoggedResult(InternalCommand, null, result, _stopwatch.ElapsedMilliseconds, null);
                _profiler.ScalarExecuted(InternalCommand, context);
            }

            return result;
        }

47. Example

Project: Projac
Source File: ConnectedSqlCommandExecutor.cs
public object ExecuteScalar(SqlQueryCommand command)
        {
            if (command == null)
                throw new ArgumentNullException("command");

            using (var dbCommand = _dbConnection.CreateCommand())
            {
                dbCommand.Connection = _dbConnection;
                dbCommand.CommandTimeout = _commandTimeout;

                dbCommand.CommandType = command.Type;
                dbCommand.CommandText = command.Text;
                dbCommand.Parameters.AddRange(command.Parameters);
                return dbCommand.ExecuteScalar();
            }
        }

48. Example

Project: ActivityManager
Source File: SqlDataSource.cs
public void SqlSelectScalar(string query, out object result)
        {
            DbCommand command = factory.CreateCommand();
            command.CommandText = query;
            command.Connection = connection;
            if (transaction != null)
                command.Transaction = transaction;
            if (connection.State == ConnectionState.Closed)
            {
                if (permanent_connection)
                    throw new SqlException("?????????? ? ????? ?????? ???????? ?? ??????????? ????????");
                else
                    connection.Open();
            }
            result = command.ExecuteScalar();
            if (!permanent_connection)
                connection.Close();
        }

49. Example

Project: Lidarr
Source File: DataMapper.cs
public object ExecuteScalar(string sql)
        {
            if (string.IsNullOrEmpty(sql))
                throw new ArgumentNullException("sql", "A SQL query or stored procedure name is required");
            Command.CommandText = sql;

            try
            {
                OpenConnection();
                return Command.ExecuteScalar();
            }
            finally
            {
                CloseConnection();
            }
        }

50. Example

Project: LCLFramework
Source File: LIDbAccesser.cs
public Object ExecuteScalar(string sql, IList<DbParameter> parameters, CommandType commandType)
        {
            using (DbCommand command = CreateDbCommand(sql, parameters, commandType))
            {
                command.Connection.Open();
                object result = command.ExecuteScalar();
                command.Connection.Close();
                return result;
            }
        }