本文整理汇总了C#中System.Data.SqlClient.SqlCommand.ExecuteNonQueryAsync方法的典型用法代码示例。如果您正苦于以下问题:C# SqlCommand.ExecuteNonQueryAsync方法的具体用法?C# SqlCommand.ExecuteNonQueryAsync怎么用?C# SqlCommand.ExecuteNonQueryAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Data.SqlClient.SqlCommand
的用法示例。
在下文中一共展示了SqlCommand.ExecuteNonQueryAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UpdateRows
public static async Task UpdateRows()
{
string connectionString = ConfigurationManager.ConnectionStrings["ProgrammingCSharpConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("UPDATE People SET FirstName='John'", connection);
await connection.OpenAsync();
int numberOfUpdatedRows = await command.ExecuteNonQueryAsync();
Console.WriteLine("Updated {0} rows", numberOfUpdatedRows);
}
}
示例2: ExecuteNonQueryAsyncWithRetry
public static Task<int> ExecuteNonQueryAsyncWithRetry(
SqlCommand command,
CancellationToken cancellationToken,
IRetryPolicy retryPolicy)
{
return retryPolicy.ExecuteAsyncWithRetry(() => command.ExecuteNonQueryAsync(cancellationToken));
}
示例3: FileUpload
public async Task<ActionResult> FileUpload(IEnumerable<HttpPostedFileBase> files)
{
var result = new List<FileUpload>();
foreach (var file in files)
{
byte[] data = new byte[file.ContentLength];
await file.InputStream.ReadAsync(data, 0, file.ContentLength);
string fileName = Path.GetFileName(file.FileName);
int Id;
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SamplesDb"].ConnectionString))
{
using (var comm = new SqlCommand(
"INSERT INTO Files (FileName, Data, ContentType)" +
" VALUES(@FileName, @Data, @ContentType);" +
" SELECT @Id=SCOPE_IDENTITY()", conn))
{
comm.Parameters.AddWithValue("@FileName", fileName);
comm.Parameters.AddWithValue("@Data", data);
comm.Parameters.AddWithValue("@ContentType", file.ContentType);
comm.Parameters.Add(new SqlParameter("@Id", System.Data.SqlDbType.Int)).Direction = System.Data.ParameterDirection.Output;
await conn.OpenAsync();
await comm.ExecuteNonQueryAsync();
Id = (int)comm.Parameters["@Id"].Value;
result.Add(new FileUpload { Id = Id, FileName = fileName,ContentType=file.ContentType });
}
}
}
return View(result);
}
示例4: InsertPurchaseOrderHeaderAsync
public static async Task InsertPurchaseOrderHeaderAsync(string cnStr)
{
const string queryString =
"INSERT INTO Purchasing.PurchaseOrderHeader " +
"(RevisionNumber, Status, EmployeeID, VendorID, ShipMethodID, OrderDate, ShipDate, SubTotal, TaxAmt, Freight, ModifiedDate) " +
"VALUES " +
"(@RevisionNumber, @Status, @EmployeeID, @VendorID, @ShipMethodID, @OrderDate, @ShipDate, @SubTotal, @TaxAmt, @Freight, @ModifiedDate)";
var dt = DateTime.UtcNow;
using (var cn = new SqlConnection(cnStr))
{
using (var cmd = new SqlCommand(queryString, cn))
{
cmd.Parameters.AddWithValue("@RevisionNumber", 1);
cmd.Parameters.AddWithValue("@Status", 4);
cmd.Parameters.AddWithValue("@EmployeeID", 258);
cmd.Parameters.AddWithValue("@VendorID", 1580);
cmd.Parameters.AddWithValue("@ShipMethodID", 3);
cmd.Parameters.AddWithValue("@OrderDate", dt);
cmd.Parameters.AddWithValue("@ShipDate", dt);
cmd.Parameters.AddWithValue("@SubTotal", 123.40M);
cmd.Parameters.AddWithValue("@TaxAmt", 12.34M);
cmd.Parameters.AddWithValue("@Freight", 5.76M);
cmd.Parameters.AddWithValue("@ModifiedDate", dt);
await cn.OpenAsync().ConfigureAwait(false);
await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
}
示例5: Send
public Task Send(Message[] messages)
{
if (messages == null || messages.Length == 0)
{
return TaskAsyncHelper.Empty;
}
SqlConnection connection = null;
try
{
connection = new SqlConnection(_connectionString);
connection.Open();
using (var cmd = new SqlCommand(_insertSql, connection))
{
cmd.Parameters.AddWithValue("Payload", JsonConvert.SerializeObject(messages));
return cmd.ExecuteNonQueryAsync()
.Then(() => connection.Close()) // close the connection if successful
.Catch(ex => connection.Close()); // close the connection if it explodes
}
}
catch (SqlException)
{
if (connection != null && connection.State != ConnectionState.Closed)
{
connection.Close();
}
throw;
}
}
示例6: 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();
}
}
示例7: InsertHttpRequestLogAsync
public async Task InsertHttpRequestLogAsync(HttpRequestLog request)
{
using (var conn = new SqlConnection(_connectionString))
{
await conn.OpenAsync();
var cmd = new SqlCommand("uspInsertRequestLog", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Id", request.Id);
cmd.Parameters.AddWithValue("@UserName", request.UserName);
cmd.Parameters.AddWithValue("@UserIpAddress", request.UserIpAddress);
cmd.Parameters.AddWithValue("@HttpAction", request.HttpAction);
cmd.Parameters.AddWithValue("@RequestUrl", request.RequestUrl);
cmd.Parameters.AddWithValue("@RequestHeader", request.RequestHeader);
cmd.Parameters.AddWithValue("@RequestBody", request.RequestBody);
cmd.Parameters.AddWithValue("@UserAgent", request.UserAgent);
cmd.Parameters.AddWithValue("@DeviceInfo", request.DeviceInfo);
cmd.Parameters.AddWithValue("@BrowserInfo", request.BrowserInfo);
cmd.Parameters.AddWithValue("@IsAnonymous", request.IsAnonymous);
cmd.Parameters.AddWithValue("@IsAuthenticated", request.IsAuthenticated);
cmd.Parameters.AddWithValue("@IsGuest", request.IsGuest);
cmd.Parameters.AddWithValue("@IsSystem", request.IsSystem);
cmd.Parameters.AddWithValue("@RequestTimeStamp", request.RequestTimeStamp);
await cmd.ExecuteNonQueryAsync();
conn.Close();
}
}
示例8: AddStatistic
private async Task AddStatistic(SqlConnection con, PackageResult package)
{
const string sql = @"MERGE dbo.PackageStatistics AS t
USING
(
SELECT @name as 'Name', @latestSupportType as 'LatestSupportType'
) AS s
ON t.Name = s.Name
WHEN MATCHED THEN
UPDATE SET LatestSupportType = s.LatestSupportType, [Count] = [Count] + 1
WHEN NOT MATCHED THEN
INSERT (Name, LatestSupportType, Count)
VALUES (s.Name, s.LatestSupportType, 1);";
try
{
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@name", package.PackageName);
cmd.Parameters.AddWithValue("@latestSupportType", package.SupportType.ToString());
await cmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Exception writing statistic {stat}", package.PackageName);
}
}
示例9: Delete
public async Task Delete()
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var command = new SqlCommand("DROP TABLE Customers", connection);
await command.ExecuteNonQueryAsync();
}
}
示例10: ExecuteAsync
public async Task ExecuteAsync(ScriptFile script, BuildItem.BuildActionType action)
{
if(action == BuildItem.BuildActionType.Drop || action == BuildItem.BuildActionType.DropAndCreate)
{
string cmdText = string.Format("DROP {0} [{1}].[{2}]", script.ScriptObject.ObjectType.ToString(), script.ScriptObject.SchemaName, script.ScriptObject.ObjectName);
var cmd = new SqlCommand(cmdText, Connection);
await cmd.ExecuteNonQueryAsync();
}
}
示例11: CreateDatabase
private async Task CreateDatabase()
{
using(var connection = _localDbInstance.CreateConnection())
{
await connection.OpenAsync();
using(var command = new SqlCommand($"CREATE DATABASE {_databaseName}", connection))
{
await command.ExecuteNonQueryAsync();
}
}
}
示例12: ExecuteQuery
private async Task<int> ExecuteQuery(string connectionString, string query)
{
using (var conn = new SqlConnection(connectionString))
{
await conn.OpenAsync();
using (var cmd = new SqlCommand(query, conn))
{
return await cmd.ExecuteNonQueryAsync();
}
}
}
示例13: Update
public static async Task Update( this Tag TagToUpdate, SqlConnection Connection, SqlTransaction Transaction = null ) {
using( SqlCommand Command = new SqlCommand() ) {
Command.Connection = Connection;
if( null != Transaction ) Command.Transaction = Transaction;
Command.CommandText = "UPDATE Tags SET Text = @Text WHERE Id = @Id;";
Command.Parameters.Add( "Text", System.Data.SqlDbType.VarChar ).Value = TagToUpdate.Text;
Command.Parameters.Add( "Id", System.Data.SqlDbType.SmallInt ).Value = TagToUpdate.Id;
await Command.ExecuteNonQueryAsync();
}
}
示例14: DeleteCacheItemAsync
public async Task DeleteCacheItemAsync(string key)
{
using (var connection = new SqlConnection(ConnectionString))
{
var command = new SqlCommand(SqlQueries.DeleteCacheItem, connection);
command.Parameters.AddCacheItemId(key);
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
}
}
示例15: CreateMessageTypeAsync
public async Task CreateMessageTypeAsync(MessageType messageType)
{
var messageTypes = new List<string>();
var validation = "NONE";
if (messageType.Validation.Equals(MessageTypeValidation.Empty))
{
validation = "EMPTY";
}
else if (messageType.Validation.Equals(MessageTypeValidation.WellFormedXml))
{
validation = "WELL_FORMED_XML";
if (messageType.Validation.XmlSchemaCollectionName != null)
{
var collection = messageType.Validation.XmlSchemaCollectionName.Escaped();
validation = $"VALID_XML WITH SCHEMA COLLECTION {collection}";
}
}
var sql = [email protected]"
IF NOT EXISTS (SELECT 1 FROM sys.service_message_types m WHERE m.name = @name)
BEGIN
CREATE MESSAGE TYPE {messageType.Name.Escaped()}
VALIDATION = {validation}
END
ELSE
BEGIN
ALTER MESSAGE TYPE {messageType.Name.Escaped()}
VALIDATION = {validation}
END
";
var command = new SqlCommand(sql, connection)
{
Parameters =
{
new SqlParameter
{
ParameterName = "@name",
Value = messageType.Name.Value,
SqlDbType = SqlDbType.NVarChar,
Size = 128,
},
}
};
await command.ExecuteNonQueryAsync();
}