0

This should be really basic and simple to do but I can seriously not find any understandable information on how to create a simple database for my nodejs typescript project.

I have installed the following packages with npm:

  • mysql2
  • sequelize
  • sequelize-cli
  • sequelize-typescript

I have attempted the following commands at the terminal

C:\repos\NodeNew>mysql2 -u root -p
'mysql2' is not recognized as an internal or external command,
operable program or batch file.

C:\repos\NodeNew>mysql -u root -p
'mysql' is not recognized as an internal or external command,
operable program or batch file.

C:\repos\NodeNew>node mysql2 -u root -p
module.js:538
    throw err;
    ^

Error: Cannot find module 'C:\repos\NodeNew\mysql2'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

C:\repos\NodeNew>

So how do I CREATE my database so I can connect to it with sequelize etc?

3 Answers 3

1

The tools you have installed are only for connecting a Node.js app to MySQL and do not include command-line tools to manage the MySQL server.

I will assume you have installed MySQL and it's running – you should then be able to find its mysql.exe command line client in the bin/ directory in the server's installation directory. If you haven't fiddled with authentication, just running it might work.

When you get to a MySQL prompt, you can follow any old instructions for creating a database; CREATE DATABASE foo; is the gist of it (authentication and permissions being a different story).

Since you're on Windows, you might want to look into HeidiSQL – it's been a while since I've used it, but it's a decent graphical MySQL management tool.

You can also use mysql2 to create the database – illustrated below – but I recommend getting a management tool.

const mysql = require('mysql2');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'mysql',
});
connection.query('CREATE DATABASE foo');
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much for your answer! I thought I had installed it before because something related to mysql keeps updating itself on my computer. But apparently I hadn't. I have something called mysql workbench or something. Anyways now I have installed Mysql server. Do you know how to tell it to put the database file in the same folder as my nodejs project? I assume I have to install mysql server on the hosting space for my website in the future?
MySQL takes care of its database files and their locations by itself, and you can't really move them around. If you need an SQL database contained in a single file, look into SQLite instead. And yes, your web host would need to support MySQL; if it's a shared server, it's usually not something you can install yourself. If it's a VPS, then sure.
hmmm interesting. So if I develop my database locally (i e put in all the info etc), how do I move it over to the server if I can't grab the files and copy/upload them to the appropriate location? Do I have to enter all data again, manually, onto the server?
No – you can use the mysqldump utility to grab a textual copy which you can then apply onto your production server.
0

You should have MySQL installed on your computer, to install mysql on Windows see the following page: MySql Once you have MySQL up and running on your computer. Open the Command Terminal and execute the following:

npm install mysql

Now you have downloaded and installed a mysql database driver. Node.js can use this module to manipulate the MySQL database:

var mysql = require('mysql');

To create a conecction create a file connection.js:

 var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

con.connect(function(err) {
 if (err) throw err;
  console.log("Connected!");
});

to test it save the file and run:

 node connection.js

Which will give you this result:

 Connected!

4 Comments

IDK I had mysql Workbench installed since before but apparently it wasn't working? Now I also have MySQL server installed. But when I try to import my mysql2 module with import mysql2 from "mysql2"; I get the error Could not find a declaration file for module 'mysql2'. 'c:/repos/NodeNew/node_modules/mysql2/index.js' implicitly has an 'any' type. Try npm install @types/mysql2` if it exists or add a new declaration (.d.ts) file containing declare module 'mysql2';ts(7016)`
@coding_pianist you dont have to make an import declare it as a variable like this: const mysql = require('mysql2'); example
Ok sweet that worked, thank you! Now I just have this error Parameter 'err' implicitly has an 'any' type.ts(7006) on the err in the function you provided con.connect(function(err) { if (err) throw err; console.log("Connected!"); });
@coding_pianist try to changue the function like this: connection.connect((err) => { if (err) throw err; console.log('Connected!'); });
0

It can be solved using beforeConnect hook of sequelize as below:

const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];

const { host, port, username, password } = config;

# create sequelize instance without providing db name in config
sequelize = new Sequelize('', username, password, config);

sequelize.beforeConnect(async (config) => {
     const connection = await mysql.createConnection({ host: host, port: port, user: username, password: password });
     await connection.query(`CREATE DATABASE IF NOT EXISTS \`${process.env.DB_NAME}\`;`);
     config.database = process.env.DB_NAME;
});

Config.json file contains configurations for different dbs like

{
  "development": {
    "username": "root",
    "password": "init@123",
    "host": "mysqldb",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": null,
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "host": "127.0.0.1",
    "dialect": "mysql",
  }
}

Database name is provided after db connection and creation(if required) in sequelize beforeConnect hook

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.