【问题标题】:How to parse SQL syntax, tokenize SQL in Python如何在 Python 中解析 SQL 语法、标记 SQL
【发布时间】:2020-12-09 03:25:54
【问题描述】:

如果存在,我需要解析 SQL 语法以获取 FROM 和 WHERE 关键字中的表名(根级别,包括子查询)。例如:

Select * 
---
From a
Inner join b on a.c = b.c
---
Where a.o in (
  select o 
  from z
  where z.l in (
      select l 
      from a
  )
)

Output: From = [a,b], Where = [z,a]

我必须处理所有类型:选择、插入、更新、删除、选择、创建

我有一些想法,例如:

  • 标记化 sql 语句
  • 查找根 FROM 的索引,如果存在根 WHERE(包括子查询)
  • 将查询拆分为 2 部分:从 FROM 到 WHERE 以及从 WHERE 到结束
  • 对于每个,使用正则表达式或一些库查找表名

我尝试了一些库:sqlparse、sql_metadata、moz_sql_parser。但是当查询复杂时它会失败。使用 sql_metadata,当评论存在时我会丢失表名,如果使用 sqlparse 删除评论,我会在某处错过')'......等等。

如何拆分 FROM 的一部分和 WHERE 的一部分 如何在每个中查找表名

如何解决?谢谢

【问题讨论】:

标签: python sql tokenize


【解决方案1】:

哈佛的 CS50 网站class 有以下代码,我认为它的最后两行可以帮助您。基本上用 result.field 调用所需的结果

  import os

  from sqlalchemy import create_engine
  from sqlalchemy.orm import scoped_session, sessionmaker

  engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from SQLAlchemy that manages connections to the database
                                                    # DATABASE_URL is an environment variable that indicates where the database lives
  db = scoped_session(sessionmaker(bind=engine))    # create a 'scoped session' that ensures different users' interactions with the
                                                    # database are kept separate

  flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall() # execute this SQL command and return all of the results
  
  for flight in flights
          print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.") # for every flight, print out the flight info

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2010-11-26
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多