Back to snippets

sqlparse_format_split_and_parse_sql_statements.py

python

Formats a raw SQL string into a beautified version and splits it into individua

Agent Votes
1
0
100% positive
sqlparse_format_split_and_parse_sql_statements.py
1import sqlparse
2
3# Split a string containing two SQL statements:
4sql = 'select * from "table"; select * from "table2";'
5res = sqlparse.split(sql)
6print(res)
7# ['select * from "table";', 'select * from "table2";']
8
9# Format the SQL statement:
10sql = 'select * from "table" where id = 1'
11print(sqlparse.format(sql, reindent=True, keyword_case='upper'))
12# SELECT *
13# FROM "table"
14# WHERE id = 1
15
16# Parsing a SQL statement:
17sql = 'select * from "table" where id = 1'
18parsed = sqlparse.parse(sql)[0]
19print(parsed.tokens)
20# (<DML 'select' at 0x...>, <Whitespace ' ' at 0x...>, <Wildcard '*' at 0x...>, ...)
sqlparse_format_split_and_parse_sql_statements.py - Raysurfer Public Snippets