0
Execute arbitrary Query in Python
One script reply has been approved by the moderators Verified

Execute an arbitrary query on a MySQL resource, more at: https://www.windmill.dev/docs/getting_started/scripts_quickstart/sql

Created by henri186 286 days ago Viewed 8605 times
0
Submitted by henri186 Python3
Verified 286 days ago
1
from typing import TypedDict
2
import mysql.connector as mysql_connector
3

4
# Define the MySQL resource type
5
class mysql(TypedDict):
6
    ssl: bool
7
    host: str
8
    port: float
9
    user: str
10
    database: str
11
    password: str
12

13
def main(mysql_credentials: mysql, query; str) -> str:
14
    # Connect to the MySQL database using the provided credentials
15
    connection = mysql_connector.connect(
16
        host=mysql_credentials["host"],
17
        user=mysql_credentials["user"],
18
        password=mysql_credentials["password"],
19
        database=mysql_credentials["database"],
20
        port=int(mysql_credentials["port"]),
21
        ssl_disabled=not mysql_credentials["ssl"],
22
    )
23

24
    # Create a cursor object
25
    cursor = connection.cursor()
26

27
    # Execute the query
28
    cursor.execute(query)
29

30
    # Fetch one result
31
    result = cursor.fetchone()
32

33
    # Close the cursor and connection
34
    cursor.close()
35
    connection.close()
36

37
    # Return the result
38
    return str(result[0])