gpt4 book ai didi

python - 如何在python中从file.sql打印表名和主键

转载 作者:太空宇宙 更新时间:2023-11-03 16:53:47 25 4
gpt4 key购买 nike

我需要使用以下程序打印表名和主键。但它不起作用。您能帮忙解决这个问题吗?我使用正则表达式模式来查找数据库架构中的表名和主键数据。

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')

文件2.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')

关于python - 如何在python中从file.sql打印表名和主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35620174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com