我需要使用以下程序打印表名和主键。但这是行不通的。您能帮忙解决这个问题吗?
我已使用正则表达式模式在数据库模式中找出表名和PRIMARY KEY数据。

class ParseCreateFile:

    begin = re.compile(r"CREATE \s+ TABLE \s+'((?:[^']|'')*)'.+(PRIMARY \s+ KEY\s? \([^)]*\))", re.IGNORECASE | re.VERBOSE | re.DOTALL)

    def __init__(self,fileName):
        self.fileName = fileName
        self.readFromFile()

    def readFromFile(self):
        try:
            file = open(self.fileName,'r')
            fileData = file.read()
            file.close()
            self.parse(fileData)
        except IOError:
            print 'Unable to read file %s' % self.fileName

    def parse(self,rawData):
        self.list = []
        while rawData:
          mo = self.begin.search(rawData)
          tablename, fil = mo.groups()
          print tablename, fil
          if mo is None:
            break
          rawData = rawData[mo.end():]

    if __name__ == '__main__':
        print "only the main classes"
        file = ParseCreateFile('file2.sql')


file2.sql

CREATE TABLE 'x'(
  'X' integer
  PRIMARY KEY(dn)
  'Y' short);
CREATE TABLE 'y'(
  'X1' integer
  PRIMARY KEY(dn1, dn2)
  'Y1' short);

Expected Out:
x: PRIMARY KEY(dn)
y: PRIMARY KEY(dn1, dn2)

最佳答案

我编辑了正则表达式,并使用了findall。

class ParseCreateFile:

    begin = re.compile(r"CREATE TABLE[ ']*([^ ']+)[ ']*[(][^/;]+(PRIMARY KEY.*)[^/;]+;", re.IGNORECASE)

    def __init__(self,fileName):
        self.fileName = fileName
        self.readFromFile()

    def readFromFile(self):
        try:
            file = open(self.fileName,'r')
            fileData = file.read()
            file.close()
            self.parse(fileData)
        except IOError:
            print 'Unable to read file %s' % self.fileName

    def parse(self,rawData):
        self.list = []
        found = self.begin.findall(rawData)
        for i in found:
            print i[0], i[1]


if __name__ == '__main__':
    print "only the main classes"
    file = ParseCreateFile('file2.sql')

10-06 12:30