Skip to main content

Connection DB

Uma biblioteca Python flexível e fácil de usar para gerenciar conexões com diferentes tipos de bancos de dados usando SQLAlchemy.

Características

  • Suporte para múltiplos bancos de dados:
    • SQL Server
    • MySQL
    • PostgreSQL
    • MongoDB (em breve)
  • Gerenciamento automático de conexões usando context manager
  • Integração com SQLAlchemy ORM
  • Tratamento de erros robusto
  • Interface consistente para diferentes bancos de dados

Instalação

pip install connection-db

Requisitos

  • Python >= 3.7
  • SQLAlchemy >= 1.4.0
  • Drivers específicos para cada banco de dados:
    • SQL Server: pymssql >= 2.2.0
    • PostgreSQL: psycopg2-binary >= 2.9.0
    • MySQL: pymysql >= 1.0.0

Uso Básico

Conexão Simples

from connection_db import DBConnection

# Usando com SQL Server
with DBConnection(
    sql_server=True,
    connection_string="mssql+pymssql://user:password@server/database"
) as db:
    db.session.execute(text("SELECT * FROM users"))
    db.session.commit()

Uso com ORM

from connection_db import DBConnection
from sqlalchemy import select
from your_models import User

with DBConnection(
    sql_server=True,
    connection_string="mssql+pymssql://user:password@server/database",
    orm_mapped=User
) as db:
    query = select(db.table).where(db.table.name == "John")
    result = db.session.execute(query)
    db.session.commit()

Padrão Repository

from connection_db import DBConnection

class BaseRepository:
    def __init__(self):
        self.connection_string = "mssql+pymssql://user:password@server/database"
        self.db_type = "sql_server"

    def get_connection(self, orm_model=None):
        return DBConnection(
            connection_string=self.connection_string,
            sql_server=(self.db_type == "sql_server"),
            orm_mapped=orm_model
        )


from connection_db import DBConnection

class Base:
    def __init__(self):
        self.connection_string = "mssql+pymssql://user:password@server/database"  # Configure uma vez
        self.db_type = "sql_server"  # ou "mysql", "postgres", etc.

    def get_connection(self, orm_model=None):
        return DBConnection(
            connection_string=self.connection_string,
            sql_server=(self.db_type == "sql_server"),
            orm_mapped=orm_model
        )

# user_repository.py
from .base_repository import Base
from .models import User

class UserRepository(Base):
    def __init__(self):
        super().__init__()
    
    def find_by_name(self, name: str):
        with self.get_connection(User) as db:
            query = select(db.table).where(db.table.name == name)
            result = db.session.execute(query)
            return result.scalars().first()
            
    def find_all(self):
        with self.get_connection(User) as db:
            query = select(db.table)
            result = db.session.execute(query)
            return result.scalars().all()

Strings de Conexão

SQL Server

mssql+pymssql://username:password@hostname:port/database_name
mssql+pyodbc://username:password@hostname:port/database_name?driver=ODBC+Driver+17+for+SQL+Server

MySQL

mysql+pymysql://username:password@hostname:port/database_name
mysql://username:password@hostname:port/database_name

PostgreSQL

postgresql://username:password@hostname:port/database_name
postgresql+psycopg2://username:password@hostname:port/database_name

Tratamento de Erros

A biblioteca inclui classes de exceção personalizadas para melhor tratamento de erros:

  • DatabaseConnectionError: Erros de conexão com o banco
  • SessionError: Problemas com a sessão do banco

Contribuindo

Contribuições são bem-vindas! Por favor, sinta-se à vontade para submeter pull requests.

Licença

Este projeto está licenciado sob a Licença MIT - veja o arquivo LICENSE para detalhes.

Autor

Miguel Tenorio

Metadata

Release files for connection-db 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for connection-db 0.5.0
File Size Uploaded Provenance Actions
connection_db-0.5.0.tar.gz 6.3 kB Without provenance Details for connection_db-0.5.0.tar.gz

Release files / connection_db-0.5.0.tar.gz

Download URL connection_db-0.5.0.tar.gz
Size 6.3 kB
Tags Source
SHA-256 checksum
How to use checksums
50fd51b1a8b2623e9fba219474dffab8557f3685e85bc2eed8eb915097b8f43c
BLAKE2b-256 checksum
How to use checksums
418b0652cb23c9cb71e36cba96d4f495f3dae483638694fc00ca4f30f46ca546
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.3

Security for connection-db 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page