Insert data into a table in MySQL

Question:

I extract data from truecar.com. This information contains price and miles of different cars. Now, I want to insert this information into a table, but my code doesn’t work to create a table and returns only ‘price’ and ‘miles’ instead of their numbers. How can I fix this?

Here is my code:

import requests
from bs4 import BeautifulSoup
import mysql.connector
car=str(input())
ur='https://www.truecar.com/used-cars-for-sale/listings/'
url=ur+car
r=requests.get(url)
soup=BeautifulSoup(r.text,'html.parser')

data = []
for card in soup.select('[class="card-content vehicle-card-body order-3 vehicle-card-carousel-
body"]'):
price = card.select_one('[class="heading-3 margin-y-1 font-weight-bold"]').text

miles = card.select_one('div[class="d-flex w-100 justify-content-between"]').text

data.append({
    'price':price,
    'miles':miles
})
print(data)

cnx = mysql.connector.connect(user='root', password='',
                              host='127.0.0.1',
                              database='truecar')
cursor = cnx.cursor()
for price,miles in data:
     cursor.execute("INSERT INTO car VALUES('%s','%s')"%(price,miles))
     cnx.commit()
cnx.close()
Asked By: Ali

||

Answers:

If you just execute the following code:

price = 10
miles = 20

data = []
data.append({
    'price':price,
    'miles':miles
})

for price, miles in data:
    print(price, miles)

The output on the console will be price miles. So you are not accessing the values of the dictionary but the keys. Therefore you do not write the keys to the database instead of the values. What works is the following code:

price = 10
miles = 20

data = []
data.append({
    'price':price,
    'miles':miles
})

for entry in data:
    print(entry["price"], entry["miles"])

I think that Saqib’s answer should also be considered, because adding the columns of the database to which the data is added will lead to fewer bugs in more complex software.

Answered By: Lenntror

If your table has the table in the database means you have to use:

INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('
   Mac', 'Mohan', 20, 'M', 2000
)

Else you need to create the new table, meaning
to execute this:

sql ='''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
)

My suggestion is to use an ORM library. Please refer to this post on SQLModel.

Answered By: Deepak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.