Python解析SQL和print语句

2024-03-28 09:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
1条回答
网友
1楼 · 发布于 2024-03-28 09:32:26

您可以使用类似sqlparse的库

import sqlparse

with open('test.sql') as input:
  statements = sqlparse.split(input.read())

for statement in statements:
  if 'create table' in statement.lower():
    print(sqlparse.format(statement, strip_comments=True))
网友
2楼 · 发布于 2024-03-28 09:32:26

我不确定解析器或解析工具,但您可以使用正则表达式进行变通。我所做的基本上是将“CREATE”和“;”之间的所有文本添加到一个列表中,然后手动添加“CREATE”和“;”以完成SQL查询

看看这个:

import re

Test = """
 
  Name: film_actor; Type: TABLE; Schema: public; Owner: postgres
 

CREATE TABLE public.film_actor (
    actor_id smallint NOT NULL,
    film_id smallint NOT NULL,
    last_update timestamp without time zone DEFAULT now() NOT NULL
);


ALTER TABLE public.film_actor OWNER TO postgres;

 
  Name: film_category; Type: TABLE; Schema: public; Owner: postgres
 

CREATE TABLE public.film_category (
    film_id smallint NOT NULL,
    category_id smallint NOT NULL,
    last_update timestamp without time zone DEFAULT now() NOT NULL
);


ALTER TABLE public.film_category OWNER TO postgres;"""

#search(r'Part 1\.(.*?)Part 3', s)

results = re.findall ( 'CREATE(.*?);', Test, re.DOTALL)

newresults = []

for x in results:
    newresults.append("CREATE "+x+";")

for y in newresults:
    print(y)

相关问题 更多 >