N
N
NbUser1432021-01-05 18:02:29
Python
NbUser143, 2021-01-05 18:02:29

How to add elements from a list to a database?

Hello!
I have a list of url addresses (more than 1000) that need to be placed in a database table. The first column should contain the url addresses themselves, and the right column should just contain the 'url' designation. As a result, nothing happened. Please tell me what is wrong.

import sqlite3

con = sqlite3.connect("base.db")
cur = con.cursor()
with con: 
    cur.execute("""
        CREATE TABLE base_url (
            url TEXT,
            name TEXT
        );
    """)


url = ['url', 'url1']

for element in url:
    con = sqlite3.connect("base.db")
    sql = 'INSERT INTO base_url(url, name) VALUES({}, url)'.format(element) # здесь element является url адресом, а url это просто обозначение для второго столбца name
    con.execute(sql)
    con.commit()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
PavelMos, 2021-01-05
@NbUser143

Quotes are needed to insert text values. And also messed up with cur and con

cur = con.cursor()
    sql = 'INSERT INTO base_url(url, name) VALUES("{}", "url")'.format(element) # здесь element является url адресом, а url это просто обозначение для второго столбца name
    print (sql)
    cur.execute(sql)
    con.commit()
con.close()

you also need to check when the table is created to see if it already exists.

K
KAVatsm, 2021-01-05
@KAVatsm

1. It looks like you misspelled the name of the while loop. Instead, you wrote With
2. did not close con and cur (the last lines should be written:
cur.close( )
con.close( )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question