LoginSignup
0
0

More than 1 year has passed since last update.

node.js(express)でmysqlに登録したデータのIDを取得する(備忘録)

Posted at

MySQLに登録したデータのIDを取得する

MySQLにデータを登録した際、auto_incrementで自動的に一意なIDが与えられる場合を想定しています

index.js
const express = require('express')
const app = express()
const mysql = require('mysql')
const cors = require('cors') // APIとして利用する場合は必要
const port = 8000

app.use(express.json())
app.use(cors()) // APIとして利用する場合は必要

const con = mysql.createConnection({
  //ご自身の環境に合わせてください
  host: 'localhost', 
  user: 'root',
  password: 'root', 
  database: 'data' 
})

// mysql接続
con.connect((err) => {
	if (err) throw err
	console.log('Connected')
})

app.post('/create', (req, res) => {
  const sql = 'insert into users (name, email, password) values (?, ?, ?)'
  con.query(sql, [req.body.name, req.body.email, req.body.password],(err, result) => {
    if(err) console.log(err)
    const id = result.inserttId //result.insertId に登録したデータのIDが格納されている
    return res.json(id)
  })
}) 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0