In this code example, data is updated from a MySQL database. First, a connection to the database is established, then the value of a specific database table column is changed.
With the SQL UPDATE statement, specific values must be specified for each table to be changed and a where clause must be used to define which rows are affected by the change
def main():
connection = connectMySQLDB()
setLastSyncTimestamp(connection)
# --------------------------------------------------
# MySQL Database Connection
# --------------------------------------------------
def connectMySQLDB():
try:
connection = mysql.connector.connect(
host=server,
database=database,
user=username,
password=password
)
if connection.is_connected():
return connection
except Error as e:
print("Error while connecting to MySQL Database: ", e)
sys.exit(1)
def setLastSyncTimestamp(connection):
cursor = connection.cursor()
currentTime = datetime.now()
timestamp = round(currentTime.timestamp())
# create new timestamp
cursor.execute("UPDATE [dbo].[last-sync] SET timestamp = ?", timestamp)
connection.commit()
cursor.close()