I do have troubles with my sql scripts which I've wrote priorely and try to read with my python code and also execute it. Here my simple mysql script, where the DELIMITER command is removed:
DROP FUNCTION IF EXISTS `employee_db`.`func_create_token`;
CREATE FUNCTION `employee_db`.`func_create_token`() RETURNS VARCHAR(100) DETERMINISTIC
BEGIN
DECLARE `chars` VARCHAR(26);
DECLARE `charLen` INT;
DECLARE `randomPassword` VARCHAR(100);
SET `chars` = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
SET `charLen` = LENGTH(`chars`);
SET `randomPassword` = '';
WHILE LENGTH(`randomPassword`) < 12 DO
SET `randomPassword` = CONCAT(`randomPassword`, SUBSTRING(`chars`, CEILING(RAND() * `charLen`), 1));
END WHILE;
RETURN `randomPassword`;
END;
I'm able to execute it directly and the function is created. No problems so far. But trying to read the sql file in python and executing it then, leads always to errors which I somehow can't solve. Below you see the python function:
# Function to execute sql file
def execute_sql_script(path_to_sql: os.PathLike[str], title: str) -> None:
# Read sql file from folder `sql`
try:
with open(path_to_sql, 'r') as f:
queries : list = f.read().split(';')
queries : list = [q.strip() for q in queries if q.strip()]
f.close()
except FileNotFoundError as f:
print(color.BOLD + color.RED + f'File couldn\'t be read. Please check error: {e}' + color.END)
# Execute sql script with progress bar
try:
with alive_bar(len(queries), dual_line = True, title = title, force_tty = True) as bar:
for _, query in enumerate(queries):
sleep(.05)
cursor.execute(query)
bar()
cursor.commit()
except Error as e:
print(color.BOLD + color.RED + f'Error in executing sql script. Check error: {e}' + color.END)
The error message is not very helpful:
Create Function - Employee |███▋⚠︎ | (!) 1/11 [
[1m[91mError in executing sql script. Check error: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3[0m
Curiously the execution of every other script which creates the tables does work fantastically and without any exceptions.
Create Function - Employee |████████████████████████████████████████| 27/27 [100