search

Home  >  Q&A  >  body text

MySQL NODEJS: A Complete Guide to Creating Databases and Related Tables

<p>I'm setting up a mysql/nodejs application. </p> <p>I want to drop the database, recreate the database, and create the tables every time the server restarts. </p> <p>If I specify a connection to the database: </p> <pre class="brush:js;toolbar:false;">let con = mysql.createConnection({ host: "localhost", user: "root", password: "pass", database: "my_db", }); </pre> <p>I can create tables, indexes, and insert values, but only the first time. Every time after that it tells me that everything has been created. </p> <p>On the other hand, if I don't specify the database when creating the connection, I can drop the database, create a new one, but when I try to create the table, I get an error saying I don't have a database associated with the table . </p> <p>Is there any way to solve this problem? </p>
P粉682987577P粉682987577521 days ago575

reply all(1)I'll reply

  • P粉231112437

    P粉2311124372023-08-27 00:24:06

    You don’t need to use a 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);
        });
    });

    Then use

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

    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 just to show the idea and split it into separate functions.

    reply
    0
  • Cancelreply