Psycopg2 connect()TypeError

时间:2018-10-24 19:22:08

标签: python python-3.x postgresql psycopg2 psql


嗨,我正尝试一如既往地连接到我的数据库。我曾经这样做,并且一切正常,我还创建了该数据库 如果我在python Terminal中做同样的事情-一切正常-我可以轻松地连接到数据库并执行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'

1 个答案:

答案 0 :(得分:0)

实际上我终于找到了问题-我引用的是不存在的connect()函数,我应该这样写: cnx, cursor = create_connection() 稍后我还发现了其他一些错误,例如PRIMARY_KEY而不是PRIMARY KEY。现在,我终于成功添加了数据库。抱歉浪费您的时间:)