如何使用Django和python中的预准备语句查询将数据插入数据库

时间:2017-07-08 06:58:57

标签: python django sqlite

我需要使用Django和Python中的预处理语句查询将表单数据插入sqlite3 db。我在下面解释我的代码。

models.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')

这里我需要通过运行预处理语句查询将所有数据保存到数据库中。

1 个答案:

答案 0 :(得分:1)

Python的SQLite库没有预处理语句对象,但它们允许您使用参数化查询,并提供多组参数。

<div id="inline1" class="audit-form" style="display: none;">
  <form class="infusion-form" id="infusion-form">
  <h3 style="color: #002046;">Sign Up For a Free Capability Audit </h3>
  <div class="dis_block clearfix">
    <div class="form-group">
      <label>First Name *</label>
      <input required class="form-control" id="inf_field_FirstName" name="inf_field_FirstName" type="text" />
    </div>
    <div class="form-group">
      <label>Last Name *</label>
      <input required id="inf_field_LastName" name="inf_field_LastName" type="text" class="form-control" />
    </div>
    <div class="form-group">
      <label>Email *</label>
      <input required id="inf_field_Email" name="inf_field_Email" type="email" class="form-control" />
    </div>
    <div class="form-group">
      <label>Confirm Email *</label>
      <input required id="inf_field_Phone1" name="inf_field_Phone1" type="email" class="form-control" />
    </div>
    <div class="form-group" style="text-align: center;">
      <input type="hidden" name="action" value ="save_procurement_data" />
      <input type="submit" id="frm_basic_info" class="btn custom-btn" value="NEXT" />

    </div>
  </div>
  </form>
  </div>