我需要使用Python将数据插入SQLite3数据库。我已经编写了查询,但它没有像我预期的那样工作。我在下面解释我的代码。
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()
这里我给出了动态值,没有数据插入到表中。
答案 0 :(得分:2)
您需要将变量的值放入SQL语句中。最安全的方法是使用以下内容
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 ))
请注意,变量作为元组传递,以便可以在SQL语句中使用它们的值。
答案 1 :(得分:1)
除了@ Code-Apprentice:
您可以使用executemany
插入多个值:
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)
]
)