简体   繁体   中英

Can i run a python script on my raspberry pi when a trigger is triggered in Mysql database server?

I'm woriking on a project that checks if LEDSTATUS from a database has the value "0" then led is off, if the value is "1" led is on. I searched and found out that there is something called UDF that can run scripts but am not sure if it is possible if the database is not local (on a server). is it possible? if yes how?

I created two python scripts one that turn led on and the other one to turns it off.

I will create a database with one table LEDSTATUS and will create a trigger that will run when ever the value of LEDSTATUS gets changed, if the value is 0 then run python script that turn led off, and if the value is 1 run the other script.

If you don't have access to the remote database server, then probably not.

You could run a cronjob (or any scheduled task) that periodically checks the database and runs the appropriate script, but there will be a delay between when the database changes and your script runs depending on how often it runs.

EDIT (4/2/2019)

I don't think a trigger is the right solution. Triggers are meant to run queries internally when some action is performed, not fire off external scripts. There may be ways to accomplish this, but I'm not familiar with any so I can't give any advice on that.

I would recommend one of two options:

  1. Write a python script that periodically checks your database (this is called polling ) for the LED status and interacts with the raspberry pi to update the LED.

  2. Put your database behind an API which can update both the database and the LED, and change whatever is updating the LED status database directly to instead interact with the API. Flask is a great python web framework you could use, and the requests package can be used to interact with it.

I would recommend option 1, but option 2 would be simpler to implement. Both solutions could be run from your raspberry pi.

Database triggers are for DELETE, INSERT, UPDATE sql queries. You cannot trigger a python script with it.

At some point you set the database field to 0 or to 1 with an UPDATE SQL query.

The event based approach is to run the according python script before or after you performed the sql update query. Python could run as a webserver on the pi and you can send values via GET or POST.

The polling approach is to query the database every x (mili)second with a python script or similar and execute turn on/off functions accordingly.

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