如何用Python 3.5生成Oracle建表SQL语句?
生成Oracle CREATE TABLE SQL语句的Python实现
嘿,这事儿其实挺简单的,咱们直接用Python的字符串拼接和字典遍历就能搞定!我给你写个适配Python 3.5版本的直观实现:
# 你的列名与数据类型字典 adict1 = {'col1': 'Number', 'col2': 'Date', 'col3': 'Date'} # 第一步:把每个键值对转换成「列名 数据类型」的格式 column_defs = [f"{column} {data_type}" for column, data_type in adict1.items()] # 第二步:拼接成完整的CREATE TABLE语句 sql_stmt = f"create table dummy({', '.join(column_defs)})" # 打印验证结果 print(sql_stmt)
运行这段代码后,sql_stmt里的内容就是你想要的:
create table dummy(col1 Number, col2 Date, col3 Date)
关于列顺序的小提醒
要注意:Python 3.5的字典不保证插入顺序,如果你的列顺序有严格要求(比如必须按col1、col2、col3的顺序排列),可以用两种方式解决:
- 用
OrderedDict定义列信息(需要导入collections模块):from collections import OrderedDict adict1 = OrderedDict([('col1', 'Number'), ('col2', 'Date'), ('col3', 'Date')]) - 或者指定列的顺序列表,按该顺序遍历字典:
desired_order = ['col1', 'col2', 'col3'] column_defs = [f"{col} {adict1[col]}" for col in desired_order]
这样就能完美生成符合你需求的SQL语句啦!
内容的提问来源于stack exchange,提问作者joe
相关产品推荐
相关产品推荐

