Cómo utilizar SQLite3 en Node.js (documentación completa y clarificada para principiantes)

Aprende a utilizar SQLite3 en Node.js con nuestra documentación completa y clara para principiantes. Comienza tu proyecto con facilidad.

4 nov 2025 • 3 min read • Q2BSTUDIO Team

Uso de SQLite3 en Node.js

SQLite3 es una base de datos basada en archivo, sin servidor y perfecta para proyectos ligeros, prototipos o como almacenamiento embebido en aplicaciones de escritorio, herramientas CLI o backends pequeños. Un solo archivo .db contiene toda la base de datos y se puede versionar o mover fácilmente.

Instalacion y panel grafico: para usar SQLite3 en Node.js instala los paquetes necesarios con npm y una herramienta de administracion web con el comando npm install sqlite3 sqlite3-admin. Para ver la base de datos visualmente ejecuta npx sqlite3-admin app.db o cambia app.db por el nombre de tu archivo.

Conexion basica: crea un archivo db.js con el siguiente codigo de ejemplo para abrir o crear el archivo app.db

const sqlite3 = require(`sqlite3`).verbose(); const db = new sqlite3.Database(`./app.db`);

Crea una tabla: ejemplo para crear una tabla users si no existe

db.run(`CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT )`, (err)=>{ if(err) console.log(`Error: `, err); else console.log(`Tabla creada`); });

Insercion de datos: siempre usa placeholders para evitar inyeccion SQL. Ejemplo:

const name = `John`; const email = `johndoe@example.com`; db.run(`INSERT INTO users(name, email) VALUES(?, ?)`, [name, email], function(err){ if(err) console.log(`Error: `, err); console.log(`Inserted row ID: `, this.lastID); });

Lectura de datos: para obtener varias filas usa db.all y para una sola fila usa db.get

db.all(`SELECT * FROM users`, [], (err, rows)=>{ if(err) throw err; rows.forEach(row=>{ console.log(row.id, row.name, row.email); }); });

Actualizacion: ejemplo para actualizar el nombre de un usuario por id

db.run(`UPDATE users SET name=? WHERE id=?`, [`Mike Tyson`, 1], function(err){ if(err) throw err; console.log(`Rows changed: `, this.changes); });

Eliminacion: ejemplo para borrar por id

db.run(`DELETE FROM users WHERE id=?`, [1], function(err){ if(err) throw err; console.log(`Rows deleted: `, this.changes); });

Cerrar la base de datos: usa db.close() cuando la aplicacion vaya a terminar. Buena practica: cerrar solo al salir de la app para evitar errores de concurrencia.

Operaciones en serie: cuando necesitas garantizar el orden de ejecucion usa db.serialize para ejecutar las consultas una a una

db.serialize(()=>{ db.run(`CREATE TABLE IF NOT EXISTS posts(id INTEGER PRIMARY KEY, title TEXT)`); db.run(`INSERT INTO posts(title) VALUES(?)`, [`Hello world`]); db.all(`SELECT * FROM posts`, [], (err, rows)=>{ console.log(rows); }); });

Resumen de buenas practicas: usar placeholders para prevenir inyeccion SQL, controlar errores en callbacks, cerrar la conexion al finalizar, y usar serialize cuando el orden de ejecucion importa. SQLite3 es ideal para prototipos, aplicaciones a medida y para integrarlo en soluciones multiplataforma donde no se necesita un servidor de base de datos completo.

Sobre Q2BSTUDIO: en Q2BSTUDIO somos una empresa de desarrollo de software a medida y aplicaciones a medida especializada en inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio y automatizacion de procesos. Podemos integrar SQLite3 en proyectos más amplios o migrar datos a soluciones gestionadas en la nube. Si buscas una aplicacion personalizada consulta nuestro servicio de Desarrollo de aplicaciones a medida y para soluciones avanzadas de IA visita nuestra pagina de IA para empresas. Incorporamos agentes IA, soluciones de Power BI y estrategias de ciberseguridad para entregar proyectos robustos y escalables.

Palabras clave: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat