简体   繁体   中英

How to set up SQL Server listener in c#

I've been trying to figure out how to set up a listener on a database table from my C# code. I've been trying most recently to set up a SqlDependency , but I've gotten stuck because the database I'm trying to apply the procedure on is read-only and I don't have the permissions to change that (yet).

Does anyone know of other ways to go about setting something like this up? My overall goal is to allow my application to listen to a database and be notified when there is an INSERT, UPDATE, etc. and to provide specifically what was changed (ie which row).

EDIT: I don't have access to the code which inserts / updates the database, all that I have is read-only access to the database itself.

You'll want to set up a SqlDependency and subscribe to the OnChangeEventHandler . See the example from docs.microsoft.com :

void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
    // Assume connection is an open SqlConnection.

    // Create a new SqlCommand object.
    using (SqlCommand command=new SqlCommand(
        "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers",
        connection))
    {

        // Create a dependency and associate it with the SqlCommand.
        SqlDependency dependency=new SqlDependency(command);
        // Maintain the reference in a class member.

        // Subscribe to the SqlDependency event.
        dependency.OnChange+=new
           OnChangeEventHandler(OnDependencyChange);

        // Execute the command.
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Process the DataReader.
        }
    }
}

// Handler method
void OnDependencyChange(object sender,
   SqlNotificationEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency.
    SqlDependency.Stop(connectionString, queueName);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM