当前位置: 首页>>代码示例>>C#>>正文


C# SqlCommand.ExecuteScalarAsync方法代码示例

本文整理汇总了C#中System.Data.SqlClient.SqlCommand.ExecuteScalarAsync方法的典型用法代码示例。如果您正苦于以下问题:C# SqlCommand.ExecuteScalarAsync方法的具体用法?C# SqlCommand.ExecuteScalarAsync怎么用?C# SqlCommand.ExecuteScalarAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Data.SqlClient.SqlCommand的用法示例。


在下文中一共展示了SqlCommand.ExecuteScalarAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TransactionSample

        private static async Task TransactionSample()
        {
            using (var connection = new SqlConnection(GetConnectionString()))
            {
                await connection.OpenAsync();
                SqlTransaction tx = connection.BeginTransaction();

                try
                {
                    string sql = "INSERT INTO Sales.CreditCard (CardType, CardNumber, ExpMonth, ExpYear)" +
                        "VALUES (@CardType, @CardNumber, @ExpMonth, @ExpYear); " +
                        "SELECT SCOPE_IDENTITY()";
                    var command = new SqlCommand();
                    command.CommandText = sql;
                    command.Connection = connection;
                    command.Transaction = tx;
                    var p1 = new SqlParameter("CardType", SqlDbType.NVarChar, 50);
                    var p2 = new SqlParameter("CardNumber", SqlDbType.NVarChar, 25);
                    var p3 = new SqlParameter("ExpMonth", SqlDbType.TinyInt);
                    var p4 = new SqlParameter("ExpYear", SqlDbType.SmallInt);
                    command.Parameters.AddRange(new SqlParameter[] { p1, p2, p3, p4 });
                
                    command.Parameters["CardType"].Value = "MegaWoosh";
                    command.Parameters["CardNumber"].Value = "08154711128";
                    command.Parameters["ExpMonth"].Value = 4;
                    command.Parameters["ExpYear"].Value = 2019;


                    object id = await command.ExecuteScalarAsync();
                    WriteLine($"record added with id: {id}");

                    command.Parameters["CardType"].Value = "NeverLimits";
                    command.Parameters["CardNumber"].Value = "987654321011";
                    command.Parameters["ExpMonth"].Value = 12;
                    command.Parameters["ExpYear"].Value = 2025;


                    id = await command.ExecuteScalarAsync();
                    WriteLine($"record added with id: {id}");
                    // throw new Exception("abort");

                    tx.Commit();
                }
                catch (Exception ex)
                {
                    WriteLine($"error {ex.Message}, rolling back");
                    tx.Rollback();
                }
            }
        }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:50,代码来源:Program.cs

示例2: Check

 public override async Task<HealthCheckStatus> Check()
 {
     using (var connection = new SqlConnection(_connectionString))
     {
         await connection.OpenAsync().ConfigureAwait(false);
         var cmd = new SqlCommand("select 1", connection);
         await cmd.ExecuteScalarAsync().ConfigureAwait(false);
         return HealthCheckStatus.Passed();
     }
 }
开发者ID:thedillonb,项目名称:Owin.HealthCheck,代码行数:10,代码来源:SqlHealthCheck.cs

示例3: Insert

		public static async Task Insert( this Tag NewTag, SqlConnection Connection, SqlTransaction Transaction = null ) {
			using( SqlCommand Command = new SqlCommand() ) {
				Command.Connection = Connection;
				if( null != Transaction ) Command.Transaction = Transaction;

				Command.CommandText = "INSERT Tags ( Text ) OUTPUT INSERTED.Id VALUES ( @Text )";
				Command.Parameters.Add( "Text", System.Data.SqlDbType.VarChar ).Value = NewTag.Text;

				NewTag.Id = (short)await Command.ExecuteScalarAsync();
			}
		}
开发者ID:freestylecoder,项目名称:DevSpace2015,代码行数:11,代码来源:Tag.cs

示例4: GetLastId

        public Task<long?> GetLastId()
        {
            var connection = CreateAndOpenConnection();
            var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
            var cmd = new SqlCommand(_getLastIdSQL.Replace("{TableName}", MessageTableName), connection, transaction);

            return cmd.ExecuteScalarAsync<long?>()
                .ContinueWith(t =>
                {
                    connection.Close();
                    return t.Result;
                });
        }
开发者ID:abuhmead1987,项目名称:Presentations,代码行数:13,代码来源:SQLMessageStore.cs

示例5: NonBlockingDatabaseOperations

        /// <summary>
        /// Performs a sequence of non blocking database operations.
        /// </summary>
        private async static Task NonBlockingDatabaseOperations()
        {
            // Build the database connection.
            using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleHttpApplication"].ConnectionString))
            {
                // Open the database connection.
                await sqlConnection.OpenAsync();

                // Insert the database row.
                SqlCommand insertSqlCommand = new SqlCommand("INSERT INTO [Session] VALUES('" + Guid.NewGuid() + "', 'Session Alpha', '2012-06-27 10:05:45'); SELECT CAST(SCOPE_IDENTITY() AS INT);", sqlConnection);
                int sessionID = (int)await insertSqlCommand.ExecuteScalarAsync();

                // Select the database row.
                SqlCommand selectSqlCommand = new SqlCommand("SELECT * FROM [Session] WHERE [SessionID] = " + sessionID, sqlConnection);
                SqlDataReader sqlDataReader = await selectSqlCommand.ExecuteReaderAsync();
                await sqlDataReader.ReadAsync();
                sqlDataReader.Close();

                // Update the database row.
                SqlCommand updateSqlCommand = new SqlCommand("UPDATE [Session] SET [SessionCode] = '" + Guid.NewGuid() + "', [Name] = 'Session Beta', [StartDate] = '2013-07-28 11:06:46' WHERE [SessionID] = " + sessionID, sqlConnection);
                await updateSqlCommand.ExecuteNonQueryAsync();

                // Delete the database row.
                SqlCommand deleteSqlCommand = new SqlCommand("DELETE FROM [Session] WHERE [SessionID] = " + sessionID, sqlConnection);
                await deleteSqlCommand.ExecuteNonQueryAsync();
            }
        }
开发者ID:AnilAwadh,项目名称:Sample-Http-Application,代码行数:30,代码来源:Program.cs

示例6: GenerateMessageId

 public Task<long> GenerateMessageId(string key)
 {
     var connection = CreateAndOpenConnection();
     var transaction = connection.BeginTransaction(IsolationLevel.ReadUncommitted);
     var cmd = new SqlCommand(_getMessageIdSql.Replace("{TableName}", MessageTableName), connection, transaction);
     cmd.Parameters.AddWithValue("EventKey", key);
     return cmd.ExecuteScalarAsync<long>()
         .ContinueWith(idTask =>
                       {
                           // We purposely don't commit the transaction, we just wanted the ID anyway, not the record
                           connection.Close();
                           return idTask;
                       })
         .Unwrap();
 }
开发者ID:paulbatum,项目名称:SignalR.WindowsAzure,代码行数:15,代码来源:SqlMessageIdGenerator.cs

示例7: Register

        public async Task<bool> Register()
        {
            bool success = false;
            Exception err = null;
            string sql = "INSERT INTO dbo.Users (facebook_id, gender, email, name, first_name, last_name, isAnonymous) OUTPUT INSERTED.id VALUES (@facebook_id, @gender, @email, @name, @first_name, @last_name, @isAnonymous)";

            if (db.State != ConnectionState.Open)
                await db.OpenAsync();
            SqlTransaction trans = db.BeginTransaction();

            try
            {
                SqlCommand cmd = new SqlCommand(sql, db, trans);
                cmd.Parameters.AddWithValue("@facebook_id", facebook_id);
                cmd.Parameters.AddWithValue("@gender", gender);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@name", name);
                cmd.Parameters.AddWithValue("@last_name", last_name);
                cmd.Parameters.AddWithValue("@first_name", first_name);
                cmd.Parameters.AddWithValue("@isAnonymous", isAnonymous);
                object id = await cmd.ExecuteScalarAsync();

                if (id != null && id.GetType() == typeof(Guid))
                {
                    this.id = ((Guid)id);
                    success = true;
                }

                trans.Commit();
            }
            catch (Exception e)
            {
                err = e;
                trans.Rollback();
            }
            finally
            {
                db.Close();
            }

            if (err != null)
            {
                throw err;
            }

            return success;
        }
开发者ID:icelsj,项目名称:ShopProtWeb,代码行数:47,代码来源:User.cs

示例8: Create

        public async Task<bool> Create()
        {
            bool success = false;
            Exception err = null;
            string sql = "INSERT INTO dbo.ItemLists (name, description, status, created_by, category, category_id, group_id) OUTPUT INSERTED.id VALUES (@name, @description, @status, @created_by, @category, @category_id, @group_id)";

            if (db.State != ConnectionState.Open)
                await db.OpenAsync();
            SqlTransaction trans = db.BeginTransaction();

            try
            {
                SqlCommand cmd = new SqlCommand(sql, db, trans);
                cmd.Parameters.AddWithValue("@name", name);
                cmd.Parameters.AddWithValue("@description", description);
                cmd.Parameters.AddWithValue("@status", status);
                cmd.Parameters.AddWithValue("@created_by", created_by);
                cmd.Parameters.AddWithValue("@category", category);
                cmd.Parameters.AddWithValue("@category_id", category_id);
                cmd.Parameters.AddWithValue("@group_id", group_id);
                object id = await cmd.ExecuteScalarAsync();

                if (id != null && id.GetType() == typeof(Guid))
                {
                    this.id = ((Guid)id);
                    success = true;
                }

                trans.Commit();
            }
            catch (Exception e)
            {
                err = e;
                trans.Rollback();
            }
            finally
            {
                db.Close();
            }

            if (err != null)
            {
                throw err;
            }
            this.created_at = DateTime.Now;
            return success;
        }
开发者ID:icelsj,项目名称:ShopProtWeb,代码行数:47,代码来源:ItemList.cs

示例9: LinkDevice

        public async Task<bool> LinkDevice()
        {
            bool success = false;
            Exception err = null;
            string sql = "INSERT INTO dbo.DeviceOwners (device_id, user_id) OUTPUT INSERTED.id VALUES (@device_id, @user_id)";

            if (db.State != ConnectionState.Open)
                await db.OpenAsync();
            SqlTransaction trans = db.BeginTransaction();

            try
            {
                SqlCommand cmd = new SqlCommand(sql, db, trans);
                cmd.Parameters.AddWithValue("@device_id", device.id);
                cmd.Parameters.AddWithValue("@user_id", user.id);
                object id = await cmd.ExecuteScalarAsync();

                if (id != null && id.GetType() == typeof(Guid))
                {
                    this.id = ((Guid)id);
                    success = true;
                    this.linked_at = DateTime.Now;
                }

                trans.Commit();
            }
            catch (Exception e)
            {
                err = e;
                trans.Rollback();
            }
            finally
            {
                db.Close();
            }

            if (err != null)
            {
                throw err;
            }

            return success;
        }
开发者ID:icelsj,项目名称:ShopProtWeb,代码行数:43,代码来源:DeviceOwner.cs

示例10: Create

        /// <summary>
        /// Creates the specified CourseSchedule data row.
        /// </summary>
        public async Task Create(IDatabaseConnection databaseConnection, CourseScheduleDataRow courseScheduleDataRow)
        {
            // Build the SQL command.
            using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO [CourseSchedule] VALUES (@courseScheduleCode, @sessionID, @dayOfWeek, @time); SELECT CAST(SCOPE_IDENTITY() AS INT);"))
            {
                // Use the specified database connection.
                SqlConnection sqlConnection = (databaseConnection as DatabaseConnection).SqlConnection;
                sqlCommand.Connection = sqlConnection;

                // Set the SQL command parameter values.
                this.SetSqlCommandParameterValues(sqlCommand, courseScheduleDataRow, setPrimaryKeyValue: false);

                // Execute the SQL command.
                int courseScheduleID = (int)await sqlCommand.ExecuteScalarAsync();

                // Assign the generated CourseScheduleID.
                courseScheduleDataRow.CourseScheduleID = courseScheduleID;
            }
        }
开发者ID:AnilAwadh,项目名称:Sample-Http-Application,代码行数:22,代码来源:CourseScheduleDataAccessComponent.cs

示例11: Create

        public async Task<bool> Create()
        {
            bool success = false;
            Exception err = null;
            string sql = "INSERT INTO dbo.Memberships (user_id, group_id, status) OUTPUT INSERTED.id VALUES (@user_id, @group_id, @status)";

            if (db.State != ConnectionState.Open)
                await db.OpenAsync();
            SqlTransaction trans = db.BeginTransaction();

            try
            {
                SqlCommand cmd = new SqlCommand(sql, db, trans);
                cmd.Parameters.AddWithValue("@user_id", user_id);
                cmd.Parameters.AddWithValue("@group_id", group_id);
                cmd.Parameters.AddWithValue("@status", status);
                object id = await cmd.ExecuteScalarAsync();

                if (id != null && id.GetType() == typeof(Guid))
                {
                    this.id = ((Guid)id);
                    success = true;
                }

                trans.Commit();
            }
            catch (Exception e)
            {
                err = e;
                trans.Rollback();
            }
            finally
            {
                db.Close();
            }

            if (err != null)
            {
                throw err;
            }

            return success;
        }
开发者ID:icelsj,项目名称:ShopProtWeb,代码行数:43,代码来源:Membership.cs

示例12: Create

        /// <summary>
        /// Creates the specified Session data row.
        /// </summary>
        public async Task Create(IDatabaseConnection databaseConnection, SessionDataRow sessionDataRow)
        {
            // Build the SQL command.
            using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO [Session] VALUES (@sessionCode, @name, @startDate); SELECT CAST(SCOPE_IDENTITY() AS INT);"))
            {
                // Use the specified database connection.
                SqlConnection sqlConnection = (databaseConnection as DatabaseConnection).SqlConnection;
                sqlCommand.Connection = sqlConnection;

                // Set the SQL command parameter values.
                this.SetSqlCommandParameterValues(sqlCommand, sessionDataRow, setPrimaryKeyValue: false);

                // Execute the SQL command.
                int sessionID = (int)await sqlCommand.ExecuteScalarAsync();

                // Assign the generated SessionID.
                sessionDataRow.SessionID = sessionID;
            }
        }
开发者ID:AnilAwadh,项目名称:Sample-Http-Application,代码行数:22,代码来源:SessionDataAccessComponent.cs

示例13: Load

        public async Task<object> Load(Type valueType, string user, string name, Type storageType)
        {
            const string sql =
                "SELECT [Value] " +
                "FROM [dbo].[Settings] " +
                "WHERE [Type] = @Type " +
                "  AND (@User IS NULL OR [User] = @User) " +
                "  AND (@Name IS NULL OR [Name] = @Name)";

            using (var connection = CreateConnection())
            {
                var command = new SqlCommand(sql, connection);

                command.Parameters.AddWithValue("@Type", valueType.FullName);
                command.Parameters.AddWithValue("@User", (object)user ?? DBNull.Value);
                command.Parameters.AddWithValue("@Name", (object)name ?? DBNull.Value);

                var value = await command.ExecuteScalarAsync();

                return Convert.ChangeType(value, storageType);
            }
        }
开发者ID:tobper,项目名称:Domo,代码行数:22,代码来源:SqlServerSettingsStorageProvider.cs

示例14: SaveFileMetaDataAsync

        /// <inheritdoc/>
        public async Task<int> SaveFileMetaDataAsync(FileMetaDataToStore metaData)
        {
            int fileId;

            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = new SqlCommand("InsertFileMetaData", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.AddWithValue("@FileName", metaData.FileName);
                    command.Parameters.AddWithValue("@MimeType", metaData.MimeType);
                    command.Parameters.AddWithValue("@ApplicationName", metaData.ApplicationName);
                    command.Parameters.AddWithValue("@InternalStoragePath", metaData.StoragePath);
                    command.Parameters.AddWithValue("@Checksum", metaData.Checksum);

                    await connection.OpenAsync();
                    fileId = Convert.ToInt32(await command.ExecuteScalarAsync());
                }
            }

            return fileId;
        }
开发者ID:NaosProject,项目名称:Naos.FileStorage,代码行数:24,代码来源:FileMetaDataRepository.cs

示例15: WriteZonesAsync

        private static async Task<IDictionary<string, int>> WriteZonesAsync(IEnumerable<string> zones)
        {
            var dictionary = new Dictionary<string, int>();

            var cs = ConfigurationManager.ConnectionStrings["tzdb"].ConnectionString;
            using (var connection = new SqlConnection(cs))
            {
                var command = new SqlCommand("[Tzdb].[AddZone]", connection) { CommandType = CommandType.StoredProcedure };
                command.Parameters.Add("@Name", SqlDbType.VarChar, 50);

                await connection.OpenAsync();

                foreach (var zone in zones)
                {
                    command.Parameters[0].Value = zone;
                    var id = (int)await command.ExecuteScalarAsync();
                    dictionary.Add(zone, id);
                }

                connection.Close();
            }

            return dictionary;
        }
开发者ID:nanaka22,项目名称:SqlServerTimeZoneSupport,代码行数:24,代码来源:Program.cs


注:本文中的System.Data.SqlClient.SqlCommand.ExecuteScalarAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。