python - For 循环检查表是否存在,如果不存在则在继续执行脚本之前创建它
问题描述
我正在尝试编写一个 for 循环来检查我的 postgres 表是否已经存在,如果它不存在,则在继续脚本的其余部分之前创建它。如果它确实存在,则不必费心创建它,而是继续脚本(将文件写入数据库)。
在某处,我的 for 循环中的某些内容不正确。有人有想法吗?
"""A tool for saving files to and from a postgresql db.
"""
import os
import sys
import argparse
import psycopg2
db_conn_str = "postgresql://word:word@111.11.111.1:5432/DBNAME"
create_table_stm = """
CREATE TABLE files (
id serial primary key,
orig_filename text not null,
file_data bytea not null
)
"""
check_for_table = """
IF EXISTS (SELECT * FROM files)
"""
def main(argv):
parser = argparse.ArgumentParser()
parser_action = parser.add_mutually_exclusive_group(required=True)
parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB")
parser_action.add_argument("--fetch", type=int, help="Fetch an image from the DB and store it in the named file, overwriting it if it exists. Takes the database file identifier as an argument.", metavar='42')
parser.add_argument("filename", help="Name of file to write to / fetch from")
args = parser.parse_args(argv[1:])
conn = psycopg2.connect(db_conn_str)
curs = conn.cursor()
# Check if the table already exists
if curs.execute(check_for_table) is None:
# If it DOES NOT exist, create it
curs.execute(create_table_stm)
# If it DOES exist, ??
elif
if args.store:
with open(args.filename,'rb') as f:
filedata = psycopg2.Binary(f.read())
curs.execute("INSERT INTO files(id, orig_filename, file_data) VALUES (DEFAULT,%s,%s) RETURNING id", (args.filename, filedata))
print curs
returned_id = curs.fetchone()[0]
print("Stored {0} into DB record {1}".format(args.filename, returned_id))
conn.commit()
elif args.fetch is not None:
with open(args.filename,'wb') as f:
curs.execute("SELECT file_data, orig_filename FROM files WHERE id = %s", (int(args.fetch),))
(file_data, orig_filename) = curs.fetchone()
f.write(file_data)
print("Fetched {0} into file {1}; original filename was {2}".format(args.fetch, args.filename, orig_filename))
conn.close()
if __name__ == '__main__':
main(sys.argv)
解决方案
您可以使用create table if not exists
并继续。
create_table_stm = """
CREATE TABLE IF NOT EXISTS files (
id serial primary key,
orig_filename text not null,
file_data bytea not null
)
"""
需要注意的是,可能已经存在具有相同名称但不同模式(即不同列和类型)的表。Postgres 不会验证它是否与您的 create 语句匹配,只会验证表名是否匹配。
如果您只需要创建一个具有特定模式的全新空白表,请drop table if exists files
使用create table files
.
推荐阅读
- python - two BoxSizers interfere
- c++ - 是否可以解释为什么返回 21
- jquery - 使用ajax在Django中将数据下载为Excel文件
- javascript - 使用带有 React.useEffect 的事件监听器
- python - 自我对象和非自我对象之间有什么区别,特别是在 Tkinter 类中?
- docusignapi - 对现有用户的 `/users` 的 POST 请求会导致重新发送激活电子邮件
- tableau-api - 如何复制 Tableau 数据提取逻辑?
- angular - 将现有的 Ionic / Firebase 项目部署到新的 Firebase 托管项目
- c# - VS 2019 无法通过实体框架加载 MySQL 数据库
- java - 将 Spring Boot 2.2.6 迁移到 Spring Boot 2.3.0 时的问题