我需要在 Django 和 Python 中使用准备好的语句查询将表单数据插入到 SQLite3 数据库中。我的代码如下:
模型.py:
class Meeting(models.Model):
"""In this class the columns for Meeting table has declared"""
room_name = models.CharField(max_length=200)
from_date = models.DateTimeField(default=datetime.now, blank=True)
to_date = models.DateTimeField(default=datetime.now, blank=True)
no_seat = models.CharField(max_length=200)
projector = models.CharField(max_length=200)
video = models.CharField(max_length=200)
created_date = models.DateTimeField(default=datetime.now, blank=True)
在这里,我已经通过迁移创建了表。我views.py
的如下:
import sqlite3
def insert(request):
""" This function helps to insert all booking data into database """
conn = sqlite3.connect("db.sqlite3")
cursor = conn.cursor()
if request.method == 'POST':
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')
在这里,我需要通过运行准备好的语句查询将所有数据保存到数据库中。
Python 的 SQLite 库没有准备好的语句对象,但它们允许您使用参数化查询,并提供一组以上的参数。
values_to_insert = [(location_name,rname,........other_fields)]
cursor.execute("""
INSERT INTO some_table ('location_name', 'rname','..... other_fields')
VALUES (?, ?, ?, ?, total fields = total ? marks)""", values_to_insert)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句