KEMBAR78
Node Jswith My SQL | PDF | My Sql | Data Management Software
0% found this document useful (0 votes)
10 views5 pages

Node Jswith My SQL

The document contains JavaScript code for managing a MySQL database, including connecting to the database, creating a users table, and performing CRUD operations (Create, Read, Update, Delete) on user records. It demonstrates both callback-based and promisified query methods for handling database interactions. Each operation is encapsulated in separate files, ensuring modularity and clarity in the code structure.

Uploaded by

Asma Eman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

Node Jswith My SQL

The document contains JavaScript code for managing a MySQL database, including connecting to the database, creating a users table, and performing CRUD operations (Create, Read, Update, Delete) on user records. It demonstrates both callback-based and promisified query methods for handling database interactions. Each operation is encapsulated in separate files, ensuring modularity and clarity in the code structure.

Uploaded by

Asma Eman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

1. db.

js
// db.js
const mysql = require('mysql');

const connection = mysql.createConnection({


host: 'localhost',
user: 'root',
password: '', // replace with your password
database: 'testdb' // make sure this DB exists
});

connection.connect(err => {
if (err) throw err;
console.log('Connected to MySQL');
});

module.exports = connection;

2. createTable.js
// createTable.js
const db = require('./db');

const query = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
)
`;

db.query(query, (err, result) => {


if (err) throw err;
console.log('Table created or already exists');
});
3. insertUsers.js
// insertUser.js
const db = require('./db');

const name = Ahmad;


const email = 'ahmad@example.com';

db.query(
'INSERT INTO users (name, email) VALUES (?, ?)',
[name, email],
(err, result) => {
if (err) throw err;
console.log('Inserted user with ID:', result.insertId);
}
);
4. selectUsers.js
// selectUsers.js
const db = require('./db');

db.query('SELECT * FROM users', (err, results) => {


if (err) throw err;
console.log('Users:', results);
});
5. updateUsers.js
// updateUser.js
const db = require('./db');

const id = 1;
const newName = Ahmad Updated';
const newEmail = 'ahmad.updated@example.com';

db.query(
'UPDATE users SET name = ?, email = ? WHERE id = ?',
[newName, newEmail, id],
(err, result) => {
if (err) throw err;
console.log(`Updated ${result.affectedRows} row(s)`);
}
);
6. deleteUsers.js
// deleteUser.js
const db = require('./db');

const id = 1;

db.query('DELETE FROM users WHERE id = ?', [id], (err, result) => {


if (err) throw err;
console.log(`Deleted ${result.affectedRows} row(s)`);
});
2. db.js — Connection with Promisified Query
// db.js
const mysql = require('mysql');
const util = require('util');

const connection = mysql.createConnection({


host: 'localhost',
user: 'root',
password: '', // your MySQL password
database: 'testdb'
});

connection.connect(err => {
if (err) throw err;
console.log('Connected to MySQL');
});

// Promisify the query method


connection.query = util.promisify(connection.query);

module.exports = connection;
3. createTable.js
// createTable.js
const db = require('./db');

(async () => {
try {
await db.query(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
)
`);
console.log('Table created.');
} catch (err) {
console.error(' Error:', err);
} finally {
db.end();
}
})();
4. insertUser.js
// insertUser.js
const db = require('./db');

(async () => {
try {
const result = await db.query('INSERT INTO users (name, email) VALUES
(?, ?)', [
abc, abc@example.com'
]);
console.log(' Inserted ID:', result.insertId);
} catch (err) {
console.error(' Error:', err);
} finally {
db.end();
}
})();
5. selectUsers.js
// selectUsers.js
const db = require('./db');

(async () => {
try {
const users = await db.query('SELECT * FROM users');
console.log('Users:', users);
} catch (err) {
console.error(' Error:', err);
} finally {
db.end();
}
})();

6. updateUser.js
// updateUser.js
const db = require('./db');

(async () => {
try {
const result = await db.query('UPDATE users SET name = ?, email = ?
WHERE id = ?', [
'Updated abcd, xyz@updated.com', 1
]);
console.log(`Updated ${result.affectedRows} row(s)`);
} catch (err) {
console.error('Error:', err);
} finally {
db.end();
}
})();
7. deleteUser.js
// deleteUser.js
const db = require('./db');

(async () => {
try {
const result = await db.query('DELETE FROM users WHERE id = ?', [1]);
console.log(`Deleted ${result.affectedRows} row(s)`);
} catch (err) {
console.error(' Error:', err);
} finally {
db.end();
}
})();

You might also like