pr3/python/datenbanken/datenbanken.ipynb

97 lines
2.2 KiB
Plaintext
Raw Permalink Normal View History

2023-06-26 21:48:05 +02:00
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import psycopg2\n",
"\n",
"conn = psycopg2.connect(host=\"localhost\", database=\"uni-db\", user=\"postgres\", password=\"password\")\n",
"\n",
"conn.close()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'host': 'localhost', 'database': 'uni-db', 'user': 'postgres', 'password': 'password'}\n"
]
}
],
"source": [
"from configparser import ConfigParser\n",
"\n",
"def config(filename=\"dbconfig.ini\", section=\"postgresql\"):\n",
" parser = ConfigParser()\n",
" parser.read(filename)\n",
"\n",
" db = {}\n",
" if parser.has_section(section):\n",
" params = parser.items(section)\n",
" db = {param[0] : param[1] for param in params}\n",
" else:\n",
" raise Exception(f\"Section: {section} not found in {filename}\")\n",
"\n",
" return db\n",
"\n",
"print(config())"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(2125, 'Sokrates', 'C4', 226), (2126, 'Russel', 'C4', 232), (2127, 'Kopernikus', 'C3', 310), (2133, 'Popper', 'C3', 52), (2134, 'Augustinus', 'C3', 309), (2136, 'Curie', 'C4', 36), (2137, 'Kant', 'C4', 7)]\n"
]
}
],
"source": [
"conn = psycopg2.connect(**config())\n",
"\n",
"cur = conn.cursor()\n",
"\n",
"cur.execute(\"SELECT * FROM professoren\")\n",
"\n",
"print(cur.fetchall())\n",
"\n",
"conn.close()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}