这是Python 创建表 以及字段
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15dd= {"a":"111","b":"222", .......} fds = ['"{}" {},'.format(k, fieldType(v)) for k, v in dd.items()] #列表生成式 fds_str = ''.join(fds) sql1 = """ drop table if exists "{table_name}"; CREATE TABLE "data"."{table_name}"( "id" serial primary key , """.format(table_name=name) + fds_str + """ "insert_time" timestamptz DEFAULT (now()));""" # 这个sql意思是判断表是否存在,存在删除,不存在正好,然后拼接字符串,创建字段,懂得都能看明白 cursor = conn_db.cursor() cursor.execute(sql1) conn_db.commit()
字段类型 可以仿照着改
因为我这里只有这三种类型数据 (时间2020/11/11 11:11:11,字典{“a”:“1”,…},字符串), 当然需要可以添加int 等等
因为我不知道返回的数据是想存成什么类型数据,所以呢,我大体分为三类,按照条件分开,要不然 全部varchar 哈哈哈 可省劲了
复制代码
1
2
3
4
5
6
7
8
9
10
11def fieldType(v): """返回创建表的字段属性""" v = str(v) if type(v) == int else v v = '' if not v else v if '/' in str(v): return 'timestamptz' elif type(v) == dict or (type(v) == list and type(v[0]) == dict): return "jsonb" else: return 'VARCHAR(255)'
我知道 你肯定还为动态插入数据犯愁 哈哈哈哈 准备好了
复制代码
1
2
3
4
5
6
7
8
9
10
11dd= {"a":"111","b":"222", .......} key_list = list(dd.keys()) key_str = ', '.join( map(lambda key: '"{}"'.format(key), key_list) ) # 这句话 不好解释,看看内置函数map用法 sql = """insert into "data"."{}" ({}) values ({})""".format(name, key_str, ', '.join(['%s'] * len(key_list))) cursor.execute(sql, [jsonDumps(IfTimes(dd[key])) for key in key_list])
插入数据相关函数
复制代码
1
2
3
4
5
6
7
8
9
10
11# 因为我的数据有特殊 所以存成了json字典格式,所以呢 序列化 def jsonDumps(data): “”“就是将我要存储的字典数据 序列化为字符串”“” if type(data) == dict or (type(data) == list and type(data[0]) == dict): return json.dumps(data) else: return data
复制代码
1
2
3
4
5
6
7
8
9
10from pytz import timezone cst_tz = timezone('Asia/Shanghai') def IfTimes(tm): """将时间格式的数据转化""" try: new_time = datetime.strptime(tm, "%Y/%m/%d %H:%M:%S").astimezone(cst_tz) return new_time except Exception as e: return tm
就这样吧,撤了,不会私聊q 2510638482
最后
以上就是壮观烧鹅最近收集整理的关于python动态创建表以及字段的全部内容,更多相关python动态创建表以及字段内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复