Node.jsMySQLテーブルの作成


テーブルの作成

MySQLでテーブルを作成するには、「CREATETABLE」ステートメントを使用します。

接続を作成するときは、必ずデータベースの名前を定義してください。

「customers」という名前のテーブルを作成します。

var mysql = require('mysql');

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

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table created");
  });
});

上記のコードを「demo_create_table.js」というファイルに保存し、ファイルを実行します。

「demo_create_table.js」を実行します

C:\Users\Your Name>node demo_create_table.js

これはあなたにこの結果を与えるでしょう:

Connected!
Table created


主キー

テーブルを作成するときは、レコードごとに一意のキーを持つ列も作成する必要があります。

これは、各レコードに一意の番号を挿入する「INT AUTO_INCREMENTPRIMARYKEY」として列を定義することで実行できます。1から始まり、レコードごとに1ずつ増加します。

テーブルを作成するときに主キーを作成します。

var mysql = require('mysql');

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

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

テーブルがすでに存在する場合は、ALTERTABLEキーワードを使用します。

既存のテーブルに主キーを作成します。

var mysql = require('mysql');

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

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table altered");
  });
});