0

I am setting up mysql/nodejs app.

I would like to delete database, recreate it and create table on each server restart.

If I specify connection with database:

let con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "pass",
  database: "my_db",
});

I can create table, indexes, insert values but just first time. Every subsequent time it will tell me that everything is already created.

If on the other hand I do not put database when I create connection, I can delete database, create new one, but when I try to create a table I get an error that I don't have a database associated with this table.

Any idea how to get around this?

2 Answers 2

1

you don't need the database in the connection

var pool  = mysql.createPool({
      connectionLimit : 10,
      host            : 'example.org',
      user            : 'bobby',
      password        : 'pass'
    });

after that you can create the database

pool.getConnection(function(err, connection){
    if(err){
        return cb(err);
    }
    connection.query("CREATE DATABASE mydb", function(err, data){
        connection.release();
        cb(err, data);
    });
});

and use

connection.changeUser({database : "mydb"});

to connect to the newly created database

pool.getConnection(function(err, connection){
    if(err){
        return cb(err);
    }
    connection.changeUser({database : "mydb"});
  let createTodos = `create table if not exists mytable(
                          id int primary key auto_increment,
                          title varchar(255)not null,
                          testdata tinyint(1) not null default 0
                      )`;

  connection.query(createTodos, function(err, results, fields) {
    if (err) {
      console.log(err.message);
    };
});

This is split ito seperate function only to show the idea.

Sign up to request clarification or add additional context in comments.

Comments

0
  1. Doing it manually.
    • If the user you are connected with is having all the privileges like a superuser, you can code it to drop database every time the server starts up (like in server.js or app.js depending upon your design) by executing the following.
    DROP {DATABASE | SCHEMA} [IF EXISTS] db_name;
    
    • PS: This is not something to be done in production environment so make sure you either remove it before final deployment or make it run as per env when env!=production.
  2. Using a DB migration library for example -> https://db-migrate.readthedocs.io/en/latest/Getting%20Started/commands/#dbdrop
    • DB dropping/recreating is not the primary use case of migration(migration = making changes to DB automatically when server boots), migration in itself is a process which is automated by these libraries.

2 Comments

But I can't code it up? Meaning I drop and create database with con.query and then once that is finished I create a table and somehow associate it with this database?
Right, you need to put it in that sequence where first the conditional dropping happens and later the creation, also check the updated answer.

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.