added sql stuff

This commit is contained in:
2022-11-25 12:55:49 +01:00
parent aea7c693d6
commit 0c233cdce8
11 changed files with 365 additions and 0 deletions

63
Freitag/db_insert.py Normal file
View File

@@ -0,0 +1,63 @@
#! /usr/bin/env python3
#
#Benötigt python3-pymysql
# mysql -h notebook14 -u python -pvilla inventory
import sys
import pymysql
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
# Passwort aus Konfigiruationsdaten lesen
credentials = dict(
host = 'notebook14',
user = 'python',
password = 'villa',
database = 'inventory'
)
def list_hosts(connection):
cursor = connection.cursor()
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
#ermittlung cursor.fetchone() eine Zeile cursor.fetchmany() gibt vile in einer Zeile
# cursor ist Iterator
#test = [row for row in cursor]
for row in cursor:
print("{0:20} {2:15} {2}".format(*row))
def add_host(connection, args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%(name)s, %(domain)s, %(address)s)
"""
# oder mit .format(**args) {name} usw
cursor.execute(sql,args)
connection.commit()
#Connection
def main():
db = db_connect(credentials)
#list_hosts(db)
row = dict(
name='notebook999',
domain='linuxhotel.de',
address='192.168.1.254',
db = 'hosts'
)
add_host(db, row)
db.close()
hide_exception(main)