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.