import pymysql
db_host = "localhost"
db_name = "mydatabse"
table_name = "Student"
db_user = "root"
db_pass = "745269"
query_insert = "INSERT INTO " + table_name + " (stu_id, stu_name) VALUES (%s, %s) "
class Student:
id = 0
name = ""
def __init__(self, sid, name):
self.id = sid
self.name = name
def insert_record(rec):
#print((rec.id, rec.name))
con = pymysql.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
cur = con.cursor()
cur.execute(query_insert, (rec.id, rec.name))
#$cur.execute("INSERT INTO Student VALUES (%s, %s)", (3, 'Qwerty'))
r1 = Student(3, "Qwerty")
insert_record(r1)
I am trying to insert new rows to database using pymysql module. I am planning to define all queries globally like INSERT one. I guess I am missing some formatting of the queries but have not been able to point it so far. Any help is appreciated in advance.
According to https://pymysql.readthedocs.io/en/latest/user/examples.html, "connection is not autocommit by default. So you must commit to save your changes."
Which would result in:
import pymysql
db_host = "localhost"
db_name = "mydatabse"
table_name = "Student"
db_user = "root"
db_pass = "745269"
query_insert = "INSERT INTO " + table_name + " (stu_id, stu_name) VALUES (%s, %s) "
class Student:
id = 0
name = ""
def __init__(self, sid, name):
self.id = sid
self.name = name
def insert_record(rec):
#print((rec.id, rec.name))
con = pymysql.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
cur = con.cursor()
cur.execute(query_insert, (rec.id, rec.name))
#$cur.execute("INSERT INTO Student VALUES (%s, %s)", (3, 'Qwerty'))
con.commit() # Added this commit call
r1 = Student(3, "Qwerty")
insert_record(r1)