脚本的第一部分返回我的所有AD用户,其值转换为Python str:draft = [('显示名称','用户名'),]
我想将此写入我的main_associate表(Postgres 9.5),避免重复。我知道我在列表中的记录不是重复的,应该写。这不会返回任何错误,但不会写入我的记录:
try:
new_conn = psycopg2.connect("dbname='test' user='usr' host='localhost' password='pswd'")
except:
print("Unable to connect to the associates database.")
sql = """INSERT INTO main_associate(displayname,username) VALUES(%s,%s)
ON CONFLICT (username) DO NOTHING"""
one_cur = new_conn.cursor()
for grp in draft:
#print(grp)
one_cur.execute(sql, (grp[0],grp[1],))
new_conn.commit
one_cur.close()
new_conn.close()
答案 0 :(得分:0)
如果您安装sqlalchemy ...
from sqlalchemy import create_engine, MetaData
engine = create_engine('postgresql://postgres:pswd@localhost/test')
meta = MetaData()
meta.reflect(bind=engine)
table = meta.tables['main_associate']
for grp in draft:
ins = table.insert({"displayname":grp[0],"username":grp[1]}).on_conflict_do_nothing(index_elements=['username'])
engine.execute(ins)