0

I need to insert form data into SQLite3 database using prepared statement query in Django and Python. My code is below:

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)

Here I have already created the table by migrating. My views.py is below:

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

Here I need all data should save into the database by running prepared statement query.

1
  • Is this for an assignment or something? Why do you need to use prepared statements? Commented Jul 8, 2017 at 7:46

1 Answer 1

1

Python's SQLite libraries don't have prepared statement objects, but they do allow you to use parameterized queries, and to provide more than one set of parameters.

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I am doing like this cursor.execute("INSERT INTO booking_meeting VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (None, rname, from_date, to_date, seat, projector, video, now, location_name)) but here i am getting this Exception Value: local variable 'location_name' referenced before assignment error.
you need to put this statement inside the if method
great :) glad could help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.