There are many methods for monitoring database changes, one of which is SQL Dependency and Service Broker. But in this tutorial, we are going to do this without using the above tools and using a much simpler trick.
Introduction
In this article, I want to explain to you how to monitor the database without the need for SQL Dependency and Service Broker.
There are many methods to monitor database changes, one of these methods is SQL Dependency and Service Broker, but in this tutorial, we are going to do this without using the above tools and by using a much simpler trick. At first, I must explain that SQL Dependency will use a trigger in nature, and we are actually going to simulate a tool similar to SQL Dependency through this trick. For example, we have a database named Shop
, which contains a table named Product
, we intend to make any changes in the table, including inserting, editing, and deleting table records, automatically and without the need for timer control as well. Thread
, the gridview
of our program should be updated or so called Refresh
. To do this, we will first create a trigger for the Insert
action on the Product
table in SQL Server as shown below:
Consider creating triggers for deletes and updates as well. Inside our trigger, we used SP (stored procedure) xp_cmdshell
. This stored procedure was provided by Microsoft in order to access operating system commands and is defined in the master database. What you're doing inside has us using the echo command to create a file called AppTextFile on the C drive. Note that to activate the xp_cmdshell
procedure, you must execute the following trigger commands in SQL Server before creating them.
Now, in the Visual Studio environment, we will use the FileSystemWatcher
class to automatically update the gridview
. This class will monitor the file that was created by trigger. Note that we have only explained the automatic gridview
update here, with this trick that you can fully monitor even changes in fields and records.
This trick was a very easy way to monitor the data of the tables. If you have any questions or other uncertainties in this field, please leave a comment below.
History
- 7th September, 2022: Initial version