简体   繁体   中英

Why tables in a DB are not created Python

I'm trying to create a table name by date

import requests, json, sqlite3

conn = sqlite3.connect('parser_all.sqlite', check_same_thread = False)
url = 'http://127.0.0.1:8000/api/reg/'

full_page = requests.get(url, auth=("admin","admin"))
pars=json.loads(full_page.content.decode('utf-8'))

a = []
for i in pars:
    a.append(i["date_visit"])

unique = list(set(a))

def get_registers(unique):
    for i in range(len(unique)):
        register =  unique[i]
        cursor = conn.cursor()
        with conn:
            cursor.execute('CREATE TABLE IF NOT EXISTS ' + register + ' (name STRING )')
        cursor.close()

get_registers(unique)

sample data in a ['13-04-2020', '10-04-2020'].

in the end I get an error

cursor.execute('CREATE TABLE IF NOT EXISTS ' + register + ' (name STRING )')
sqlite3.OperationalError: near "13": syntax error

In your case SQL engine receive query:

CREATE TABLE IF NOT EXISTS 13-04-2020 (name STRING )

and return error because 13-04-2020 is expression, not a valid table name

You can fix it by quote table name like "13-04-2020" :

cursor.execute('CREATE TABLE IF NOT EXISTS "' + register + '" (name STRING )')

DB Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM