Skip to content

Instantly share code, notes, and snippets.

@Bucephalus-lgtm
Last active January 12, 2023 23:42
Show Gist options
  • Save Bucephalus-lgtm/bc0e8106c513fa449267666f760a359d to your computer and use it in GitHub Desktop.
Save Bucephalus-lgtm/bc0e8106c513fa449267666f760a359d to your computer and use it in GitHub Desktop.
// Create a file, say, User.js(basically this file keeps all the configurations and setup for initializing User table in the database)
// Sequelize is an ORM, right?
// So, you don't need to learn SQL to use MySQL, that's what we will do below:
// Import Sequelize from sequelize npm package
const {Sequelize, DataTypes} = require("sequelize");
const sequelize = new Sequelize(
'__your_db_name__',
'__your_db_password__',
{
host: '__your_db_host__',
dialect: 'mysql'
}
);
sequelize.authenticate().then(() => {
console.log('Database connection done successfully!!!');
}).catch((error) => {
console.error('Some error occured while connecting to database!!!', error);
});
const User = sequelize.define("usesr", {
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
});
sequelize.sync().then(() => {
console.log('User table created successfully!!!');
}).catch((error) => {
console.error('Some error occured while creating the User table : ', error);
});
// ***************************************Go to command line***************************
// Run the following command:
node User.js
Its output will be like this:
Executing (default): SELECT 1+1 AS result
Executing (default): CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) NOT NULL, `email` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Database connection done successfully!!!
Executing (default): SHOW INDEX FROM `users`
User table created successfully!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment