def insert_sample_data(self, values): # added self since you are referencing it below
with self.con.cursor() as cur:
sql = "insert into sampletable values (%s, %s, %s)" # Use %s for parameters
cur.executemany(sql, values) # Pass the list of tuples directly
self.con.commit()
list1 = [(1100, 'abc', '{"1209": "Y", "1210": "Y"}'), (1100, 'abc', None)]
self.insert_sample_data(list1) # pass the list directly
import pymysql
class Connection:
def __init__(self):
self.host = 'localhost'
self.user = 'nameit'
self.password = 'YES'
self.port = 3306
self.db = 'Xomai'
def connection(self):
db = pymysql.connect(host=self.host, user=self.user, password=self.password, port=self.port, db=self.db)
cur = db.cursor()
return db, cur
def create_table(self, cur):
sql = """CREATE TABLE `activity_feedback` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`inst_id` bigint(20) DEFAULT NULL COMMENT 'ID',
`broadcast_id` bigint(20) DEFAULT NULL COMMENT '你好',
`student_id` bigint(20) DEFAULT NULL COMMENT '学生ID',
`content` varchar(1024) DEFAULT NULL COMMENT '学员内容',
`comment` varchar(255) DEFAULT NULL COMMENT '注释',
`gmt_create` datetime DEFAULT NULL,
`gmt_modify` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `activity_feedback_student_id_index` (`student_id`)
) ENGINE = InnoDB AUTO_INCREMENT = 1050 DEFAULT CHARSET = utf8mb4 COMMENT = '学员表'"""
cur.execute(sql)
def insert(self, id, inst_id, broadcast_id, student_id, content, comment, gmt_create, gmt_modify):
sql = """INSERT INTO `activity_feedback` (
`id`, `inst_id`, `broadcast_id`, `student_id`, `content`, `comment`, `gmt_create`, `gmt_modify`)
VALUES ('{}','{}','{}','{}','{}','{}','{}','{}')""".format(id, inst_id, broadcast_id, student_id, content, comment, gmt_create, gmt_modify)
try:
self.connection()[1].execute(sql)
self.connection()[0].commit()
except:
self.connection()[0].rollback()
if __name__ == '__main__':
conn = Connection()
conn.insert(123, 123, 324, 3451, 'ajdf', 'sdfs', '2013-2-5', '2014-3-4')