【发布时间】:2019-03-29 07:30:14
【问题描述】:
您好,我正在尝试像往常一样连接到我的数据库。我曾经这样做过,一切正常,我还创建了该数据库 如果我在 python 终端中做同样的事情——一切正常——我可以轻松地连接到我的数据库并执行我的 sql 查询。我的代码:
from psycopg2 import connect
def create_connection():
cnx = connect(
user="postgres",
password="*******",
host="localhost",
dbname="exercises_db")
cnx.autocommit = True
cursor = cnx.cursor()
return (cnx, cursor)
def close_connection(cnx, cursor):
cursor.close()
cnx.close()
def create_tables():
cnx, cursor = connect()
customers = '''
CREATE TABLE customers (
customer_id serial,
name varchar(255),
surname varchar(255),
PRIMARY KEY(customer_id)
);
'''
cursor.execute(customers)
orders = '''
CREATE TABLE orders (
order_id serial,
customer_id int REFERENCES customers(customer_id),
description text,
PRIMARY KEY(order_id)
FOREIGN KEY(customer_id)
);
'''
cursor.execute(orders)
products = '''
CREATE TABLE products (
product_id serial,
name varchar(255),
price decimal(5, 2)
PRIMARY_KEY(product_id)
);
'''
cursor.execute(products)
close_connection(cnx, cursor)
create_tables()
结果是:
Traceback (most recent call last):
File "A1_1.py", line 65, in <module>
create_tables()
File "A1_1.py", line 26, in create_tables
cnx, cursor = connect()
File "A1_1.py", line 20, in connect
cnx = connect( host="localhost", database="exercises_db")
TypeError: connect() got an unexpected keyword argument 'host'
【问题讨论】:
-
Mikey,你是说这段代码曾经工作过然后停止了吗?你改变了什么?如果不是这样,有什么不同?
-
Connect 没有主机关键字。 initd.org/psycopg/docs/…
-
其实我终于找到了问题——我引用了不存在的connect()函数我应该写:cnx, cursor = create_connection()
标签: python python-3.x postgresql psycopg2 psql