Home > Software engineering >  Creating a table in postgres using pandas and psycopg2 gives me an error
Creating a table in postgres using pandas and psycopg2 gives me an error

Time:01-08

I am trying to create a database in postgres database using pandas and psycopg2. The syntax are fine but still gives me an error like: --------------------------------------------------------------------------- SyntaxError Traceback (most recent call last) Cell In[67], line 9 7 sql = "CREATE TABLE linux (Distribution, {})".format(', '.join(column_names)) 8 # Execute the statement ----> 9 cur.execute(sql) 11 # Commit the changes 12 engine.commit() SyntaxError: syntax error at end of input LINE 1: ...tion_Commitment, Forked_From, Target_Audience, Cost, Status)

These are the things i tried.

import pandas as pd
import psycopg2
engine = psycopg2.connect(dbname="pandas", user="postgres", password="root", host="localhost")

cur = engine.cursor()
# Define the table
column_names = [
                "Founder", 
                "Maintainer", 
                "Initial_Release_Year", 
                "Current_Stable_Version", 
                "Security_Updates", 
                "Release_Date", 
                "System_Distribution_Commitment", 
                "Forked_From", 
                "Target_Audience", 
                "Cost", 
                "Status"
               ]
sql = "CREATE TABLE linux (Distribution, {})".format(', '.join(column_names))
# Execute the statement
cur.execute(sql)

# Commit the changes
engine.commit()

# Close the cursor and connection
cur.close()
engine.close()

CodePudding user response:

You need to specify data type for each column like shown below.
Change data types to those that are actual in your case.

schema = [
    ("Founder", "varchar(50)"),
    ("Maintainer", "varchar(50)"),
    ("Initial_Release_Year", "date"),
    ("Current_Stable_Version", "varchar(20)"),
    ("Security_Updates", "varchar(50)"),
    ("Release_Date", "date"),
    ("System_Distribution_Commitment", "varchar(50)"),
    ("Forked_From", "date"),
    ("Target_Audience", "varchar(50)"),
    ("Cost", "numeric(10, 2)"),
    ("Status", "varchar(10)")
]
sql = "CREATE TABLE linux (Distribution varchar(30), {})"\
    .format(', '.join(map(' '.join, schema)))
  • Related