Skip to content

Instantly share code, notes, and snippets.

Created July 26, 2012 07:35
Show Gist options
  • Save clarle/3180770 to your computer and use it in GitHub Desktop.
Save clarle/3180770 to your computer and use it in GitHub Desktop.
Short tutorial on how to use Express and node-mysql
// Module dependencies
var express = require('express'),
mysql = require('mysql');
// Application initialization
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password'
var app = module.exports = express.createServer();
// Database setup
connection.query('CREATE DATABASE IF NOT EXISTS test', function (err) {
if (err) throw err;
connection.query('USE test', function (err) {
if (err) throw err;
connection.query('CREATE TABLE IF NOT EXISTS users('
+ 'PRIMARY KEY(id),'
+ 'name VARCHAR(30)'
+ ')', function (err) {
if (err) throw err;
// Configuration
// Main route sends our HTML file
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
// Update MySQL database'/users', function (req, res) {
connection.query('INSERT INTO users SET ?', req.body,
function (err, result) {
if (err) throw err;
res.send('User added to database with ID: ' + result.insertId);
// Begin listening
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
<!doctype html>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
$(document).ready(function () {
$('#user-submit').click(function () {
var payload = {
name: $('#user-name').val()
url: "/users",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(payload),
complete: function (data) {
<h3>Enter a username to enter into the database:</h3>
<input id="user-name" type="text" />
<input id="user-submit" type="submit" />
<p id="output"></p>
"name": "reddit-node-mysql"
, "description": "A demo of how to use Express and MySQL together"
, "author": "Clarence Leung <github@clarle>"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "~2.5",
"mysql": "~2.0"
Copy link

But i want to bind data from mysql to html page.

Copy link

kazup01 commented Feb 11, 2017

Thanks nice demo!

Copy link

nice demo for we bigginers

Copy link

ctosid commented Jun 26, 2018

Sorry im starting out with node so pardon me!..
Don't you think there need to be statement which closes the connection like connection.end()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment