Skript zum Einlegen von Tabellen
Verfasst: Montag 26. November 2012, 16:28
Hallo Python-Profis,
ich bin absoluter Anfänger in Python (in Programmieren allgemein)
Nun muss ich in meinem Praktikum ein Skript schreiben, mit dem man die DB anlegen kann.
Die Daten, die zur Verfügung gestellt sind, haben einen sehr komischen Format: es gibt z. B. eine .GES Datei, die Beschreibung von den Tabellen beinhaltet, eine andere, die die Formate erklärt. Die Tabellen mit deren Attributen müssen auch aus so einer Datei ausgelesen werden. Das alles habe ich irgendwie hinbekommen. Nun stehe ich vor einem Problem, das ich mit eure Hilfe hoffentlich lösen kann:
und zwar mit einer for-Schleife kommt das Programm in ein Verzeichnis, wo alle Files liegen und liesst diese nach einander ein, dabei legt an und befüllt das nach und nach die Tabellen.
Das Problem ist, dass nachdem erste Tabelle angelegt und befüllt ist, und es die zweite Datei bearbeitet, sagt es beim Anlegen/Befüllen:
Error FEHLER: Wert zu lang für Typ character(3)
Exit code: 1
wenn ich aber, das wieder laufen lasse, wird die Tabelle reibungslos angelegt, die nächste aber wieder nicht
ich wusste nicht, wie mein code poste
Wäre super, wenn ihr mir dabei hilft
Grüße Ferdinand
ich bin absoluter Anfänger in Python (in Programmieren allgemein)
Nun muss ich in meinem Praktikum ein Skript schreiben, mit dem man die DB anlegen kann.
Die Daten, die zur Verfügung gestellt sind, haben einen sehr komischen Format: es gibt z. B. eine .GES Datei, die Beschreibung von den Tabellen beinhaltet, eine andere, die die Formate erklärt. Die Tabellen mit deren Attributen müssen auch aus so einer Datei ausgelesen werden. Das alles habe ich irgendwie hinbekommen. Nun stehe ich vor einem Problem, das ich mit eure Hilfe hoffentlich lösen kann:
und zwar mit einer for-Schleife kommt das Programm in ein Verzeichnis, wo alle Files liegen und liesst diese nach einander ein, dabei legt an und befüllt das nach und nach die Tabellen.
Das Problem ist, dass nachdem erste Tabelle angelegt und befüllt ist, und es die zweite Datei bearbeitet, sagt es beim Anlegen/Befüllen:
Error FEHLER: Wert zu lang für Typ character(3)
Exit code: 1
wenn ich aber, das wieder laufen lasse, wird die Tabelle reibungslos angelegt, die nächste aber wieder nicht
ich wusste nicht, wie mein code poste

Code: Alles auswählen
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author:
#
# Created: 16.10.2012
# Copyright: (c)2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
import re, psycopg2, sys
FREE_WHEEL = re.compile
TABLE_START = re.compile(r'00K')
CREATE_ATTR = re.compile(r'00F$')
FILL_ATTR = re.compile(r'00I$')
END = re.compile(r'00E$')
INPUT_R1 = re.compile(r'01([\w\d_]+)')
INPUT_R2 = re.compile(r'02([\w\d_]+)')
INPUT_R3 = re.compile(r'03([\w\d_]+)')
INPUT_R4 = re.compile(r'04([\w\d_]+)')
INPUT_R5 = re.compile(r'05([\w\d_]+)')
INPUT_R6 = re.compile(r'06*([\w\d_]+)')
INPUT_R8 = re.compile(r'08([\w\d_]+)')
INPUT_RNUM = re.compile(r'[0-9][0-9]([\w\d_]*)')
class Attribute(object):
id=""
name=""
key=""
fill=""
typ=""
length=""
def __init__(self,id,name,key,fill,typ,length):
self.id=id
self.name=name
self.key=key
self.fill=fill
self.typ=typ
self.length=length
# def make_attr_list(id,name,key,fill,typ,length):
# list=[]
# list.append(id,name,key,fill,typ,length)
class Steuerung(object):
table_name = ""
number_of_attr = 0
attribut_id = []
attribut_name = []
is_key = []
be_NULL = []
attribut_typ = []
field_length = []
data_list = []
p_keys = []
# print (table_name +" "+ attribut+" "+ data)
sqlBuffer= ""
def __init__(self):
self.state = 'Start'
print self.state
self.f = dict({
'Start':[[TABLE_START,'K-Zustand',None],[INPUT_RNUM,'Error',None],[FILL_ATTR,'Error',None],[CREATE_ATTR,'Error',None]],
'K-Zustand':[[INPUT_R1,'TABLE_NAME',get_table_name]],
'TABLE_NAME':[[INPUT_R6,'FULL_NAME',get_table_full_name],[INPUT_RNUM,'TABLE_NAME',None]],
'FULL_NAME':[[INPUT_R8,'NUMBER_of_ATTR',get_number_of_attr],[INPUT_RNUM,'FULL_NAME',None]],
'NUMBER_of_ATTR':[[CREATE_ATTR,'F-Zustand',None],[INPUT_RNUM,'NUMBER_of_ATTR',None]],
'F-Zustand':[[INPUT_R1,'ATTR_ID',get_attr_ID]],
'ATTR_ID':[[INPUT_R2,'ATTR_NAME',get_attr_name]],
'ATTR_NAME':[[INPUT_R3,'PRIM_KEY',get_prim_key]],
'PRIM_KEY':[[INPUT_R4,'FILL_NESS',get_fill_ness]],
'FILL_NESS':[[INPUT_R5,'FIELD_TYP',get_field_typ]],
'FIELD_TYP':[[INPUT_R6,'FIELD_LENGTH',get_field_length]],
'FIELD_LENGTH':[[FILL_ATTR,'I-Zustand',None],[CREATE_ATTR,'F-Zustand',None],[INPUT_RNUM,'FIELD_LENGTH',None]],
'I-Zustand':[[END,'End',None],[TABLE_START,'K-Zustand',None],[FILL_ATTR,'I-Zustand',None],[INPUT_RNUM,'I-Zustand',feel_attributes]],
'End':[[TABLE_START,'K-Zustand',None],[INPUT_RNUM,'End',None]]
})
# list_a=[]
def handle_input(self,input):
typ_1 = ['U','V']
state,process = self.parseInput(input)
if(process != None):
process(input)
if state == 'Error':
print('Error!')
self.state=state
if process == get_table_name:
self.table_name = input[2:]
return self.table_name
elif process == get_number_of_attr:
self.number_of_attr = input[2:]
return self.number_of_attr
elif process == get_attr_ID:
self.attribut_id.append(input[2:])
return self.attribut_id
elif process == get_attr_name:
self.attribut_name.append(input[2:])
return self.attribut_name
elif process == get_prim_key:
if input[2:] == '1':
self.is_key.append('1')
else:
self.is_key.append('0')
return self.is_key
elif process == get_fill_ness:
if input[2:] == '0':
self.be_NULL.append('NOT NULL')
else:
self.be_NULL.append(' ')
return self.be_NULL
elif process == get_field_typ:
if input[2:] == 'U' or input[2:] == 'V':
self.attribut_typ.append('varchar')
else:
self.attribut_typ.append('char')
return self.attribut_typ
elif process == get_field_length:
if input[2:]=='':
self.field_length.append('100')
else:
self.field_length.append(input[2:])
return self.field_length
elif process == feel_attributes:
self.data_list.append(input[2:])
return self.data_list
def parseInput(self,input):
for tuple in self.f[self.state]:
regexp = tuple[0]
if regexp.match(input):
return (tuple[1],tuple[2])
expected = []
for tuple in self.f[self.state]:
expected.append(tuple[0].pattern)
print "In state "+self.state+": Expected one of"+str(expected)+" but got "+input
return ('Error',None)
def isFinished(self):
return self.state=='End' or self.state=='Error'
def iterChunks(self, chunk_size):
res = []
for item in self.data_list:
res.append(item)
if len(res) >= chunk_size:
yield res
res = []
if res:
yield res # yield the last, incomplete, portion
def typ(attribut_typ):
if attribut_typ == 'U' or attribut_typ == 'V':
attribut_typ = 'varchar'
else:
attribut_typ = 'char'
return attribut_typ
def get_table_name(input):
pass
def get_table_full_name(input):
pass
def get_number_of_attr(input):
pass
def get_attr_ID(input):
pass
def get_attr_name(input):
pass
def get_prim_key(input):
pass
def get_fill_ness(input):
pass
def get_field_typ(input):
pass
def get_field_length(input):
pass
def feel_attributes(input):
pass
Code: Alles auswählen
#-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author:
#
# Created: 20.11.2012
# Copyright: (c) 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
from table_sample_sm import Steuerung
from table_sample_sm import Attribute
import psycopg2
import sys, os
import string
def main():
pass
def quote(string):
return "'"+string.replace("'","''")+"'"
def replace_all(text, d):
for i, j in d.iteritems():
text = text.replace(i, j)
return text
if __name__ == '__main__':
m = Steuerung()
for file in os.listdir('E:\\abdata\\abdamed\\TESTDATEN_ABDAMED\\kkk\\'):
print file
infile = open('E:\\abdata\\abdamed\\TESTDATEN_ABDAMED\\kkk\\'+file, 'r')
for line in infile:
# print line
m.handle_input(line.strip())
if m.isFinished():
print "Parsing finished."
break
attribute_koplett = []
attribute_koplett = zip(m.attribut_id,m.attribut_name,m.is_key,m.be_NULL,m.attribut_typ,m.field_length)
#print "table_name: "+ m.table_name
#print "there are: "+ str(m.number_of_attr)
#print attribute_koplett
attrib =''
for a in m.attribut_name:
attrib+=a+','
#print attrib[:-1]
#attrib = m.attribut_name
m.attribut_id = []
m.attribut_name = []
m.is_key = []
m.be_NULL = []
m.attribut_typ = []
m.field_length = []
ucode = {'\\':'', 'A25' : u'\xc4','a25' : u'\xe4', 'O25' : u'\xd6', 'o25' : u'\xf6',
'U25' : u'\xdc', 'u25' : u'\xfc', 's39': u'\xDF'}
j = int(m.number_of_attr)
v = zip(*[iter(m.data_list)]*j)
#print v
con = None
try:
con = psycopg2.connect(database='postgres', user='postgres')
cur = con.cursor()
attributes = ''
keys = ''
for i in attribute_koplett:
attributes+=(i[1])+' '+str(i[4])+'('+str(i[5])+') '+str(i[3])+','
if str(i[2]) == '1':
keys+=str(i[1])+','
print 'creating table: '+ m.table_name
cur.execute('CREATE TABLE IF NOT EXISTS '+str(m.table_name)+'('+attributes+'PRIMARY KEY '+'('+keys[:-1]+')'+')')
for a in v:
aaa= ",".join(quote(x) for x in a)
txt = replace_all(aaa,ucode)
cur.execute ('INSERT INTO '+str(m.table_name)+'('+str(attrib[:-1])+') values (' + txt + ')')
#print txt
con.commit()
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
infile.close()
os.remove("E:\\abdata\\abdamed\\TESTDATEN_ABDAMED\\kkk\\"+file)
Grüße Ferdinand