How to insert data into SQLite3 database with Python?

半世苍凉 提交于 2021-02-20 02:55:27

问题


I need to insert data into SQLite3 database using Python. I have written the query but it's not working as I expected. My code is below.

conn = sqlite3.connect("db.sqlite3")
cursor = conn.cursor()
location_name = request.POST.get('lname')
rname = request.POST.get('rname')
seat = request.POST.get('seat')
projector = request.POST.get('projector')
video = request.POST.get('video')
location_name = location_name[0:255]
rname = rname[0:255]
seat = seat[0:10]
from_date = request.POST.get('from_date')
to_date = request.POST.get('from_date')
current_datetime = datetime.datetime.now()
now = current_datetime.strftime("%Y-%m-%d %H:%M")
cursor.execute("INSERT INTO booking_meeting (room_name,from_date,to_date,no_seat,projector,video,created_date,location_name) \ VALUES (rname, from_date, to_date, seat, projector, video, now, location_name  )")

conn.commit()

Here I am giving the dynamic value and no data is inserting into table.


回答1:


You need to put the values of your variables into the SQL statement. The safest way to do this is with something like the following

cursor.execute("INSERT INTO booking_meeting (room_name,from_date,to_date,no_seat,projector,video,created_date,location_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (rname, from_date, to_date, seat, projector, video, now, location_name ))

Note that the variables are passed as a tuple so that their values can be used in the SQL statement.




回答2:


In addition to @Code-Apprentice:

You could uses executemany to insert many values:

cursor.executemany(
  "INSERT INTO booking_meeting (room_name,from_date,to_date,no_seat,projector,video,created_date,location_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
  [
    (rname1, from_date1, to_date1, seat1, projector1, video1, now1, location_name1),
    (rname2, from_date2, to_date2, seat2, projector2, video2, now2, location_name2)
  ]
)

Furher reading



来源:https://stackoverflow.com/questions/45407767/how-to-insert-data-into-sqlite3-database-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!