0

I'm following a tutorial that requires me to create a database, normally i would have created this through phpmyadmin but i obviously can't do this. The following is the script required, i've tried the create line on my command line but it doesn't seem to work. Where do i run the database script? I'm using npm, and using my windows command line

create database test;

use test;

CREATE TABLE users (
  id int(11) NOT NULL auto_increment,
  name varchar(100) NOT NULL,
  age int(3) NOT NULL,
  email varchar(100) NOT NULL,
  PRIMARY KEY (id)
);

2 Answers 2

2

you dont have to specify database to connect to server.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  multipleStatements: true // this allow you to run multiple queries at once.
});

var sqlCommand = `
create database test;

use test;

CREATE TABLE users (
  id int(11) NOT NULL auto_increment,
  name varchar(100) NOT NULL,
  age int(3) NOT NULL,
  email varchar(100) NOT NULL,
  PRIMARY KEY (id)
);
`
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected yet no db is selected yet!");
  con.query("CREATE DATABASE users", function (err, result) {
    if (err) throw err;
    console.log("Database created");
  });
// OR allow multiple queries in createConnection and run
// con.query(sqlCommand, function (err, result) {
//    if (err) throw err;
//    console.log("Database created");
//  });

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

Comments

-1

it can be done using nodejs file, follow this code to create database in mysql

var mysql = require('mysql');

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

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table created");
  });
});

3 Comments

Thankyou, i'm following the tutorial at blog.chapagain.com.np/… Step 12 runs the create database line, it would seem like he uses the command line, is this the case?
I think he missed that part to include in js file, you can add this table creation part there
How is that supposed to create database when you're specifying 'database' in your config file? You simply will receive Unknown database 'dbname'.

Your Answer

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