首頁  >  問答  >  主體

MySQL NODEJS:建立資料庫和關聯表的完整指南

<p>我正在設定mysql/nodejs應用程式。 </p> <p>我想在每次伺服器重新啟動時刪除資料庫,重新建立資料庫,並建立表格。 </p> <p>如果我指定與資料庫的連線:</p> <pre class="brush:js;toolbar:false;">let con = mysql.createConnection({ host: "localhost", user: "root", password: "pass", database: "my_db", }); </pre> <p>我可以建立表格、索引、插入值,但只有第一次可以成功。每次以後都會告訴我已經創建了一切。 </p> <p>另一方面,如果我在建立連線時沒有指定資料庫,我可以刪除資料庫,建立新的資料庫,但是當我嘗試建立表格時,會出現一個錯誤,說我沒有與該表格關聯的資料庫。 </p> <p>有辦法解決這個問題嗎? </p>
P粉682987577P粉682987577390 天前437

全部回覆(1)我來回復

  • P粉231112437

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

    你不需要在連線中使用資料庫

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

    之後你可以建立資料庫

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

    然後使用

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

    連接到新建立的資料庫

    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);
        };
    });

    這只是為了展示思路而將其拆分為單獨的函數。

    回覆
    0
  • 取消回覆