Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Interacting with MySQL databases with Sequelize
Connor Schratz
Connor Schratz

Posted on • Edited on

     

Interacting with MySQL databases with Sequelize

Introduction to MySQL

MySQL is a relational database management system (RDBMS). Data in these types of databases are arranged into tables, which can reference other data stored in tables. This relation between data in separate tables helps to add structure to the data and gives origin to the name RDBMS. In most cases, these databases must be searched or queried using the specific syntax that the creators of the database set up. Luckily, for us, there are programs out there that allow us the freedom and flexibility to query these databases in a more Javascript like format, these types of programs are called ORMs or object-relational mapping. Sequilize is one of those programs. It handles the task of converting between objects in Javascript and the rows in a MySQL database. Let's take a look at the process of getting Sequelize set up and running on a project using a MySQL database.

Setting up a MySQL Database

Let's set up our MySQL database using the syntax provided to us by the database. Here we're creating a songs table with id, name, and artist values in the table.

CREATEDATABASEmusic;USEmusic;CREATETABLEsongs(idint(5)auto_incrementprimarykey,namechar(30),artistchar(20));insertintosongs(name,artist)values('StairwayToHeaven','LedZeppelin');insertintosongs(name,artist)values('RainSong','LedZeppelin');insertintosongs(name,artist)values('BetterNow','PostMalone');insertintosongs(name,artist)values('Congratulations','PostMalone');
Enter fullscreen modeExit fullscreen mode

When we query our database we can select the entire table by using this query:

SELECT*FROMsongs;|id|name|artist||----|--------------------|--------------||1|StairwayToHeaven|LedZeppelin||2|RainSong|LedZeppelin||3|BetterNow|PostMalone||4|Congratulations|PostMalone|
Enter fullscreen modeExit fullscreen mode

To select only the songs by Post Malone you could use this query:

SELECTnameFROMsongsWHEREartist='PostMalone';|name||-----------------||BetterNow||Congratulations|
Enter fullscreen modeExit fullscreen mode

Now that we have an understanding of how a basic database in MySQL functions, let's see how this process can be done using the Sequelize ORM!

Sequelize IMG

Creating a Database with Sequelize

Let's take a look at how setting up a database with Sequelize differs from the process described above.

// Run in the terminal to install Sequelize// and the MySQL databasenpminstall--savesequelizenpminstallmysql--save
Enter fullscreen modeExit fullscreen mode

Now we have everything set up to use Sequelize within the Javascript file to create our database and define the tables we want within in. Let's look at that process.

// Run in the Javascript fileconst{sequilize}=require('sequelize');constdb=newSequelize('music','root','',{host:'localhost',dialect:'mysql',});constSongs=db.define('Songs',{id:{type:Sequelize.INTEGER,autoIncrement:true,primaryKey:true},song:{type:Sequelize.STRING,},artist:{type:Sequelize.STRING,}});
Enter fullscreen modeExit fullscreen mode

After executing the lines of code above, we've done the exact same thing as earlier. We've created a music database using Sequelize and created a Songs table with the values of id, song, and artist. Now that we've created the database and table, let's add some data into the table like we did before. Notice how we use the 'await' keyword, this is because almost every Sequelize method is asynchronous!

constcreateData=async()=>{constcongratulations=awaitSongs.create({song:'Congratulations',artist:'Post Malone'}):constbetterNow=awaitSongs.create({song:'Better Now',artist:'Post Malone'}):conststairWay=awaitSongs.create({song:'Stairway to Heaven',artist:'Led Zeppelin'}):constrainSong=awaitSongs.create({song:'Rain Song',artist:'Led Zeppelin'}):}
Enter fullscreen modeExit fullscreen mode

Now that we've populated our data, we need to have a way to access the data we've inserted into our table, let's look at how that's done. Sequelize has a great method called findAll().

constgetData=async()=>{constgetMyMusic=awaitSongs.findAll();console.log(getMyMusic);}// Prints the following to the consoledataValues:{id:1,name:'Congratulations',artist:'Post Malone',createdAt:2020-07-19T20:20:06.450Z,updatedAt:2020-07-19T20:20:06.450Z},{id:2,name:'Better Now',artist:'Post Malone',createdAt:2020-07-19T20:20:06.450Z,updatedAt:2020-07-19T20:20:06.450Z},{id:3,name:'Stairway to Heaven',artist:'Led Zeppelin',createdAt:2020-07-19T20:20:06.450Z,updatedAt:2020-07-19T20:20:06.450Z},{id:4,name:'Rain Song',artist:'Led Zeppelin',createdAt:2020-07-19T20:20:06.450Z,updatedAt:2020-07-19T20:20:06.450Z},
Enter fullscreen modeExit fullscreen mode

The ability to use an ORM while working with databases makes life a whole lot easier. Creating your database and defining the structure can all be done within your Javascript files and doesn't require you to use the MySQL interface. Sequelize can also be used to perform specific queries of your database just like the ones in MySQL. For more information, check out theSequelize documentation. Alsothis article by Joseph Hu, really helped solidify my understanding of Sequelize as well, give it a read! I hope my article provided insight into both MySQL and Sequelize and how using an ORM can really speed up the process of creating and defining your database!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Developer at Leviton
  • Location
    New Orleans, LA
  • Education
    B.S. Neuroscience
  • Work
    Software Developer at Leviton
  • Joined

More fromConnor Schratz

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp