#! /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 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() def db_insert_into(connection, table, data): columns = [] values = [] for col in data.keys(): col = col.replace("'", '') columns.append(col) values.append('%('+col+')s') sql = """ INSERT INTO {table} ({columns}) VALUES ({placeholder}) """.format( table=table, columns=','.join(columns), placeholder=','.join(values), ) print(sql) with connection as cursor: cursor.execute(sql, data) #Connection def main(): credentials = dict( host = 'notebook14', user = 'python', password = 'villa', database = 'inventory' ) db = db_connect(credentials) #list_hosts(db) row = dict( name='notebook999', domain='linuxhotel.example', address='192.168.1.254', ) db_insert_into(db, 'hosts', row ) db.close() hide_exception(main)