Por lo general, para un proyecto de nodejs, solo sigo este ejemplo estándar:
var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db' }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); }); connection.end(); Sveltekit no permite la var mysql = require('mysql'); Así que traté de reemplazar eso con import { mysql } from 'mysql'; Que tampoco funciona. No estoy seguro si alguien tiene experiencia con esto y puede indicarme que entienda mi error.
1. Instalar el paquete mysql2
npm install --save mysql22. Configurar la conexión MySQL
lib/db/mysql.js
import mysql from 'mysql2/promise'; export const mysqlconn = await mysql.createConnection({ host: '<myhost>', user: 'root', password: 'mypassword', database: 'mydatabase' });3. Cree un punto final de API
routes/api/read.js
import { mysqlconn } from '$lib/db/mysql'; export async function get() { let results = await mysqlconn.query('SELECT * FROM mytable') .then(function([rows,fields]) { console.log(rows); return rows; }); return { body: results } }¿Cual es mejor? ¿El código anterior o este código?
1. Instalar el paquete mysql2
npm install --save mysql22. Configurar la conexión MySQL
lib/db/mysql.js
import mysql from 'mysql2/promise'; let mysqlconn = null; export function mysqlconnFn() { if (!mysqlconn) { mysqlconn = mysql.createConnection({ host: '<myhost>', user: 'root', password: 'mypassword', database: 'mydatabase' }); } return mysqlconn; }3. Cree un punto final de API
routes/api/read.js
import { mysqlconnFn } from '$lib/db/mysql'; export async function get() { let mysqlconn = await mysqlconnFn(); let results = await mysqlconn.query('SELECT * FROM mytable') .then(function([rows,fields]) { console.log(rows); return rows; }); return { body: results } } También puede configurar la conexión MySQL en hooks .
Consulte: https://github.com/sveltejs/kit/issues/1538#issuecomment-1002106271
puede algo como knex obras?
// in /src/lib/db.js import knex from 'knex' export default knex({ client: 'mysql', version: '5.7', connection: { host: '127.0.0.1', port: 3306, user: 'root', password: '', database: 'library' }, })en cualquier lugar del punto final
// in /src/routes/api/books.js import db from '$lib/db' // get all books export const get = async request => { const books= await db.select().from('books') if (voters) { return { body: { books } } } // else } // add a book export const post = async ({ body }) => { const added = await db .insert({ title: body.get('title'), author: body.get('author'), // .insert(JSON.parse(body)) // or you can send JSON.stringfy(dataObject) .into('admins') if (added) { return { status: 200, body: { message: 'A book added successfully' } } } // else }puedes buscarlo como quieras,,
esta puede no ser la respuesta apropiada, la encontré el fin de semana pasado