Expor consultas SQL com segurança
Ofereça acesso de leitura a um banco de dados sem permitir injeções.
Expor consultas SQL com segurança é uma aula grátis de MCP Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MCP Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MCP Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Databases Behind a Tool
An MCP server can give a model real data by wrapping a database behind a tool, so the AI asks questions instead of touching raw tables. 🗄️
Reads, Not Writes
For safety, start by exposing only read access. Let the model query and report, but keep inserts, updates, and deletes off the table.
The Injection Danger
Never paste model text straight into SQL. That invites SQL injection, where crafted input rewrites your query and leaks or destroys data.
query = "SELECT * FROM users WHERE id = " + user_input # unsafe!Use Parameterized Queries
The fix is parameterized queries: you write placeholders and the driver binds values safely, so input can never change the query shape.
cur.execute("SELECT * FROM users WHERE id = ?", (user_id,))Take Values as Arguments
Let the model pass values as typed arguments, then you build the query. The model supplies data, never the SQL text itself.
@mcp.tool()
def find_user(user_id: int) -> str:
...Pin the Query Shape
Keep the SQL fixed in your code and only slot in bound parameters. A locked query shape is the simplest way to stay safe.
Use a Read-Only Role
Defense in depth: connect with a database read-only user. Even a buggy tool then physically cannot modify or drop your data.
Bound the Result Size
Always cap rows with a LIMIT so one broad query cannot dump a huge table into the model and blow your token budget.
cur.execute("SELECT name FROM users LIMIT 50")Whitelist Allowed Tables
If the model picks a table, validate it against an allowlist. Reject anything not on the list instead of trusting the name.
Return Tidy Rows
Format results as clean text or simple records so the model reads them easily. Clarity in, clarity out for the next reasoning step.
Hide Sensitive Columns
Select only the columns the task needs. Leaving out secrets like password hashes keeps private data out of the model entirely.
Quick Check
What protects a SQL tool from injection?
Recap: Safe SQL
You exposed a database safely: parameterized read-only queries, allowlisted tables, and row limits. Next, wrap a web API. 🎯
Perguntas Frequentes
A aula “Expor consultas SQL com segurança” é grátis?
Sim — o texto completo de “Expor consultas SQL com segurança” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MCP Academy, atualize para CoddyKit PRO. O curso de MCP Academy inclui 4 aulas no total.
O que vou aprender em “Expor consultas SQL com segurança”?
Ofereça acesso de leitura a um banco de dados sem permitir injeções. Você pratica MCP Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar MCP Academy?
Nenhuma experiência prévia é necessária. MCP Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Expor consultas SQL com segurança”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de MCP Academy?
Sim. Cada aula de MCP Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Expor consultas SQL com segurança
- Transformar uma API REST em ferramentas
- Agrupar conexões no ciclo de vida
- Armazenar em cache e limitar a taxa dos serviços upstream