我想使用python向数据库添加一些数据,但是我遇到了问题。一个表中的数据已成功插入,但另一表有问题。
有两个表vehicles
和vehicle_price
如下:
我的代码如下:
def insert_vehicles_to_db(vehicle):
conn = db_connection()
cur = conn.cursor()
if vehicle_not_exists(vehicle, conn, cur):
try:
insert_vehicle(vehicle, conn, cur)
insert_vehicle_price(vehicle, conn, cur)
except Exception as e:
pass
conn.close()
函数insert_vehicle
如下:
def insert_vehicle(vehicle, conn, cur):
try:
query = "INSERT INTO vehicles (reference, data, price, reference_url, timestamp) VALUES (%s, %s, %s, %s, %s);"
cur.execute(query, (vehicle['reference'], "", vehicle['price'], vehicle['reference_url'], datetime.datetime.now()))
conn.commit()
except Exception as e:
pass
那很好,车辆总是插入的。但是问题出在下一个insert_vehicle_price
中,如下所示:
def insert_vehicle_price(vehicle, conn, cur):
try:
vehicle_data = get_vehicles(vehicle['reference'], vehicle['reference_url'], conn, cur)[0] # get the last vehicle
vehicle_id = vehicle_data[0]
vehicle_price = Decimal(vehicle['price'] + ".00")
query = "INSERT INTO vehicle_price (price, timestamp, vehicle_id) VALUES (%s, %s, %s);"
cur.execute(query, (vehicle_price, datetime.datetime.now(), vehicle_id))
conn.commit()
except Exception as e:
pass
因此由于某些原因未插入价格。
知道为什么吗?
更新
函数get_vehicles
如下所示:
def get_vehicles(reference, reference_url, conn, cur):
try:
sql_get_vehicles = "SELECT * FROM vehicles WHERE reference = %s and reference_url = %s"
cur.execute(sql_get_vehicles, (reference, reference_url))
return cur.fetchall()
except Exception as e:
# TODO Handle error
pdb.set_trace()
pass