I’am working on flask application, and I want to initilize the db when i start the application, so i create a schema file:
schema.sql file contains:
-- Drops
DROP TABLE IF EXISTS `article`;
DROP TABLE IF EXISTS `book`;
DROP TABLE IF EXISTS `settings`;
-- Article
CREATE TABLE `article` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(150) DEFAULT NULL,
`text` longtext DEFAULT NULL,
`created_at` date,
PRIMARY KEY (`id`)
);
-- Book
CREATE TABLE `book` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(150) DEFAULT NULL,
`description` longtext DEFAULT NULL,
`img` longtext DEFAULT NULL,
`link` longtext DEFAULT NULL,
`created_at` date,
PRIMARY KEY (`id`)
);
-- Settings
CREATE TABLE `settings` (
`id` int NOT NULL AUTO_INCREMENT,
`title` varchar(150) DEFAULT "تَربيَة الأُمةِ مِنْ جَديدٍ",
`cover_text` varchar(200) DEFAULT "{فَاعْلَمْ أَنَّهُ لَا إِلَٰهَ إِلَّا اللَّهُ}",
`admin_username` varchar(50) DEFAULT "Admin",
`admin_password` varchar(50) DEFAULT "12345",
PRIMARY KEY (`id`)
);
insert into `settings`(`title`,`cover_text`,`admin_username`,`admin_password`) values ("تَربيَة الأُمةِ مِنْ جَديدٍ","{فَاعْلَمْ أَنَّهُ لَا إِلَٰهَ إِلَّا اللَّهُ}","Admin","12345");
Then i use **executemany()** to create my database tables, I write this code:
def init_db():
_,mycursor = mysql_connector()
with current_app.open_resource('schema.sql') as f:
mycursor.executemany(f.read().decode('utf8'))
But when i run by flask --app flaskr init-db there’s problem with mycursor.executemany() function.
The Error says:
mycursor.executemany(f.read().decode('utf8'))
TypeError: CMySQLCursor.executemany() missing 1 required positional argument: 'seq_params'
Note: mysql_connector function in 1st line of the code is a function return the cursor of the mysql connector:
config = {
data...
}
def mysql_connector():
try:
g.db = mysql.connector.connect(**config)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
site_logger.exception("Something is wrong with your username or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
site_logger.exception("Database does not exist")
else:
print("Error: ", err)
site_logger.exception(err)
return
else:
# Initialize our cursor
mycursor = g.db.cursor(buffered=True)
return g.db, mycursor
I tried to change the sql code in schema.sql file but the same problem.
So where’s the problem or what’s the solution ?
>Solution :
You need to execute different SQL queries one by one but with executemany() you execute the same SQL query multiple times.
Modify your code like this
def init_db():
_, mycursor = mysql_connector()
with current_app.open_resource('schema.sql') as f:
# Split the file content by semicolon and filter out empty lines
sql_commands = [cmd.strip() for cmd in f.read().decode('utf8').split(';') if cmd.strip()]
for cmd in sql_commands:
mycursor.execute(cmd)