Home > Back-end >  Automatically create a table/database if it doesn't exist, within the code?
Automatically create a table/database if it doesn't exist, within the code?

Time:10-13

With MongoDB, if I call to add a model to a database within the code, it just creates the table and/or database for you if it doesn't exist already. With MySQL it just gives me an error until I go and manually create the table myself with all the columns it wants - even when I tried getting express-session to work (to move forward I had to create a 'sessions' table within MySQL workbench with the sid, expires, data, createdAt, and updatedAt columns).

I'm wondering if there's a way to just create it automatically if it doesn't exist or if I'm just approaching the whole thing incorrectly (i.e. I need to create it once forever and I'm good to go, even after I deploy the website.) I made a 'database.sql' page in VS Code already, but I'm not sure how and where to link it to my main code.

CodePudding user response:

Its better to manually enter a table in MySql and not in code, just maintain database.sql file which you can maintain in your repo

CodePudding user response:

MySQL's CREATE TABLE IF NOT EXISTS has existed for quite a while.

Use this either in a SQL file, and/or somewhere in the initialization part of your code.

If you've manually created the right structure in Workbench, grab the output from show create table sessions and you'll have a reproducible structure.

The advantage of SQL is its structured nature, so it shouldn't be too much a a surprise that tables aren't autocreated. With a correct structure and indexes it will perform well and contain structured data so you don't need to implement strict checks in your application code.

  • Related