我正在尝试编写一个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)
答案 0 :(得分:1)
您可以使用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
。