繁体   English   中英

如何使用Python将数据插入SQLite3数据库?

[英]How to insert data into SQLite3 database with Python?

我需要使用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()

在这里,我给出了动态值,并且没有数据插入到表中。

您需要将变量的值放入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语句中使用。

除了@ 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)
  ]
)

继续阅读

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM