Search code examples
pythondjangorawsql

Insert to mysql database through Rawsql


I want to perform custome sql query on mysql database table to store the record .What is the way to perform insert query through rawsql.

I am using following model

class Student(models.Model):
    userid = models.CharField(db_column='UserId', primary_key=True, max_length=12)  # Field name made lowercase.
    firstname = models.CharField(db_column='FirstName', max_length=30)  # Field name made lowercase.
    middlename = models.CharField(db_column='MiddleName', max_length=30, blank=True, null=True)  # Field name made lowercase.
    lastname = models.CharField(db_column='LastName', max_length=30)  # Field name made lowercase.
    password = models.CharField(db_column='Password', max_length=50, blank=True, null=True)  # Field name made lowercase.

and trying to insert values through raw method because want to store passwoed through md5('') provided by mysql:

st = Student.object.raw("Insert into Student values(%s,%s,%s,%s,md5(%s))",['ST1','Fname','Mname','Lname','Pwd']);

but i am not getting how to execute this.Is there any way ?


Solution

  • Here a simple example:

    from django.db import connections
    
    cursor = connections['default'].cursor()
    cursor.execute("INSERT INTO TABLE(field1,field2) VALUES( %s , %s )", [value1, value2])