Skip to main content

A simple class to better handle database connections using psycopg2 (PostgreSQL)

Project description

psycopg_dbconn_class

A simple class to handle database connections using psycopg2 (PostgreSQL).

Development background

When I've started to work with Python + PostgreSQL, I have begun using the pysycopg2 library. However, I do prefer working with classes, and the usual connection/cursor methods were not very functional for my applications.

Eventually, I decided to structure the objects I needed inside a DataBaseConnection class, and created this repository for further improvements.

Use

To properly use this class, just download/clone the repository and import the class in your application.

from psycopg_dbconn_class import DataBaseConnection

If you get a ImportError message, be sure to install psycopg2-binary library as well:

python -m pip install -r requirements.txt 

or

python -m pip install pycopg2-binary

Then, you can create an object, connect to a server and begin running queries. By default, parameters for connecting into the server are expected do be in environment variables ('DBN', 'DBU', 'DBK', 'DBH', 'DBP'), but you can also use a json file (conn.json). Finally, you may also enter parameters manually.

from app.psycopg_dbconn_class.src.psycopg_dbconn_class import DataBaseConnection

DB = DataBaseConnection(auto_config=False)
DB.update_config_values(name='db', host='127.0.0.0', port="15432", user="postgres", password="PostgresPass")
DB.connect()

if DB.connected:
	# For queries without need of return
	DB.run_query('INSERT INTO colum VALUES (NULL)')
	DB.run_query('INSERT INTO colum VALUES (%s)', [1])
	# For queries that need the return
	result = DB.run_read_query('SELECT * FROM table WHERE val = %s', [2], fetch_all=True)
	print(result)

DB.close()

Warranty

psycopg_dbconn_class is an open-source project. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License version 3 attached for more details.


Developed by: Kleydson Stenio @ 2023

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

psycopg_dbconn_class-0.0.1.tar.gz (19.5 kB view hashes)

Uploaded Source

Built Distribution

psycopg_dbconn_class-0.0.1-py3-none-any.whl (20.2 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page