Created
April 25, 2022 23:38
-
-
Save Magamex/e6ec07aeaf93844ca5e202faea98111c to your computer and use it in GitHub Desktop.
Ejemplo uso de mysql2 - https://www.npmjs.com/package/mysql2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mysql = require('mysql2'); | |
//Generar una conexión a la base de datos | |
const connection = mysql.createConnection({ | |
host: 'localhost', | |
user: 'root', | |
database: 'test', | |
port: 3306 | |
}); | |
module.exports = { | |
connection | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { connection } = require('./config'); | |
/** | |
* Funcion para mostrar datos de la base de datos | |
* @param {String} table Required | |
* @param {Array} columns Optional | |
* @param {Array} where Optional | |
* @returns {Promise} | |
* | |
* Ejemplo: | |
* select('trabajos',['nombreTrabajo','precio'],['precio','>',450, 'AND', 'precio','<',3000]) | |
* .then(result => { | |
* console.log(result); | |
* }) | |
*/ | |
const select = async(table=null,columns='*',where='')=>{ | |
if(table==null) | |
return await new Promise((reject)=> {reject('Error: Invalid Params')}); | |
if(columns!='*') | |
columns = columns.join(","); | |
let customWhere = ''; | |
let data = []; | |
if(where!=''){ | |
customWhere = 'WHERE '; | |
customWhere += where.join(' '); | |
} | |
return await new Promise((resolve, reject) => { | |
connection.query(`SELECT ${columns} FROM ${table} ${customWhere}`, data,(err, rows) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(rows); | |
} | |
}); | |
}); | |
} | |
select('trabajos') | |
.then(result => { | |
console.log(result) | |
}); | |
/** | |
* Funcion para insertar un dato en la base de datos | |
* @param {String} table Required | |
* @param {Array} columns Required | |
* @param {Array} data Required | |
* @returns {Promise} | |
* | |
* Ejemplo: | |
* insert('trabajos',['nombreTrabajo', 'precio', 'idLaboratorio', 'idCategoria'],['Soy una pruebita 2',50000,1,1]) | |
* .then(result => { | |
* console.log(result) | |
* }) | |
* | |
*/ | |
const insert = async(table=null, columns=null,data=null) => { | |
if(table==null || columns==null || data==null) | |
return await new Promise((reject)=> {reject('Error: Invalid Params')}); | |
const nomColumns = "`" + columns.join("`,`") + "`"; | |
let cantColumns = []; | |
columns.map(() => cantColumns.push('?')) | |
return await new Promise((resolve, reject) => { | |
connection.query(`INSERT INTO ${table} (${nomColumns}) VALUES (${cantColumns})`, data, (err, rows) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve({status:true,message:'Insertado'}); | |
} | |
}); | |
}); | |
} | |
/** | |
* Funcion para actualizar datos en la base de datos | |
* @param {String} table Required | |
* @param {Array} columns Required | |
* @param {Array} data Required | |
* @param {Array} where Required | |
* @returns {Promise} | |
* | |
* Ejemplo: | |
* update('trabajos',['nombreTrabajo','precio'],['Soy un test 1',2500],['idTrabajo',62]) | |
* .then(result => { | |
* console.log(result) | |
* }) | |
*/ | |
const update = async(table=null,columns=null,data=null,where=null)=>{ | |
if(table==null||columns==null||data==null||where==null) | |
return await new Promise((reject)=> {reject('Error: Invalid Params')}); | |
if(columns.length!=data.length) | |
return await new Promise((reject)=> {reject('Error: columns.length != data.length')}); | |
const [idLabel,idValor] = where; | |
let setColumns = ''; | |
columns.map((column,i, {length})=>{ | |
(i + 1 === length) | |
?setColumns+=`${column} = ? ` | |
:setColumns+=`${column} = ? ,` | |
}) | |
return await new Promise((resolve, reject) => { | |
connection.query(`UPDATE ${table} SET ${setColumns} WHERE ${idLabel}=${idValor}`, data, (err, rows) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve({status:true,message:'Actualizado'}); | |
} | |
}); | |
}); | |
} | |
/** | |
* Funcion para borrar un valor de la base de datos | |
* @param {String} table | |
* @param {Array} where | |
* @returns {Promise} | |
* | |
* Ejemplo: | |
* erase('trabajos',['idTrabajo',62]) | |
*/ | |
const erase = async(table=null,where=null)=>{ | |
if(table==null||where==null) | |
return await new Promise((reject)=> {reject('Error: Invalid Params')}); | |
const [idLabel,idValor] = where; | |
return await new Promise((resolve, reject) => { | |
connection.query(`DELETE FROM ${table} WHERE ${idLabel}= ?`, [idValor], (err, rows) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve({status:true,message:'Eliminado'}); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment