semvec/pypi-packages huggingface dataset:
dbcm2 2.0.3
A MySQL/MariaDB database context manager for Python
License: MIT License
Requires Python: >=3.6
Keywords: Python database context manager

# dbcm2
> The UseDatabase context manager for working with MySQL/MariaDB.  For more information, see Chapters 7, 8, 9, and 11 of the 2nd Edition of Head First Python.


The use of MariaDB over MySQL is a strong recommendation.

## Install

You can install using your choice of `pip` or `conda` as follows (with dependencies taken care of for you):

> `pip install dbcm2`

or:

> `conda install -c barrypj dbcm2`

The `dbcm2` package is based on the `DBcm` module from the 2nd edition of Head First Python.  It is essentially a thin wrapper around the `mysql-connector-python` module and exists primarily to demonstrate how to create a custom context manager in Python.  Despite this primary goal, `DBcm` can be useful when your database interactions are straightforward.  An assumption is that you know the basics of SQL (specifically: the CRUD operations).

## How to use

Begin by importing what you need from `dbcm2`:

```python
from dbcm2.DBcm import UseDatabase, SQLError
```

Note: The use of `dbcm2.DBcm` above is a breaking change from the original `DBcm` as described in the book.

Next, create a configuration dictionary detailing the credentials you are using:

```python
config = { 
    'host': '127.0.0.1',
    'user': 'usernamehere',
    'password': 'passwordhere',
    'database': 'databasenamehere',
}
```

Another assumption is that you have previously installed your database server, created a new database, granted rights to the new database to a user, then created one or more tables.  See Chapter 7 of Head First Python, 2nd Edition, for more on this.

You are now ready to use the context manager in your code.  Here's a simple example where the SQL query is sent to the server, executed, then the results (if any) are available within the `data` variable:

```python
with UseDatabase(config) as cursor:
    try:
        _SQL = "select * from log"
        cursor.execute(_SQL)
        data = cursor.fetchall()
    except SQLError as err:
        print('Your query broke:', str(err))
```

And, that's it!  Enjoy, and have fun.