Created
February 14, 2023 02:13
-
-
Save oelbaga/9e2789be304b622b9df9141544ce7b8d to your computer and use it in GitHub Desktop.
NextJS connect to My SQL db connection wrapper
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
import mysql from "mysql2/promise"; | |
export async function query({ query, values = [] }) { | |
// PlanetScale; | |
const dbconnection = await mysql.createConnection( | |
process.env.MYSQL_DATABASE_URL | |
); | |
//Digital ocean ubuntu | |
// const dbconnection = await mysql.createConnection({ | |
// host: process.env.MYSQL_HOST, | |
// database: process.env.MYSQL_DATABASE, | |
// user: process.env.MYSQL_USER, | |
// password: process.env.MYSQL_PASSWORD, | |
// }); | |
try { | |
const [results] = await dbconnection.execute(query, values); | |
dbconnection.end(); | |
return results; | |
} catch (error) { | |
throw Error(error.message); | |
return { error }; | |
} | |
} | |
//in a separate node js file you can use this wrapper like this: | |
// const productName = req.body.product_name; | |
// const addProducts = await query({ | |
// query: "INSERT INTO products (product_name) VALUES (?)", | |
// values: [productName], | |
// }); |
Where is the table description or create table sql script?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
big thanks!