static void Main()

{

    // Delete record in Sql Server database .\SQLEXPRESS using integrated security

    // Where databasename is Testing

    // Table name is MyTable

    // Where id=1

    DeleteRecord(@"System.Data.SqlClient", @"Data Source=.\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True", "MyTable", "id", 1);

}

 

/// <summary>

/// Deletes record from database/table

/// </summary>

/// <typeparam name="T">Type of field</typeparam>

/// <param name="providerName">Provider invariant name</param>

/// <param name="connectionString">Connection string</param>

/// <param name="tableName">Name of the table where record is to be deleted</param>

/// <param name="fieldName">Name of the field which is used when deleting</param>

/// <param name="value">Value of the field ’fieldName’ which is used when comparing rows</param>

/// <returns>How many records where affected</returns>

private static int DeleteRecord<T>(string providerName, string connectionString, string tableName, string fieldName, T value)

{

    // Create factory object using provider name

    var factory = System.Data.Common.DbProviderFactories.GetFactory(providerName);

    // Create connection and remember to dispose it

    using (var connection = factory.CreateConnection())

    {

        connection.ConnectionString = connectionString;

       

        // Create command

        var command = connection.CreateCommand();

        command.CommandText = string.Format(@"DELETE FROM {0} WHERE {1} = @value", tableName, fieldName);

 

        // Create parameter using the factory object

        var parameter = factory.CreateParameter();

        parameter.ParameterName = "value";

        parameter.Value = value;

        command.Parameters.Add(parameter);

 

        // Open connection, execute query and close connection

        connection.Open();

        int result = command.ExecuteNonQuery();

        connection.Close();

 

        // And we are done

        return result;

    }

}

About these ads