时间:2022-03-04 11:23:36 | 栏目:Python代码 | 点击:次
数据库中最好插入Null值。
在python中,暂时没找到通过sql语句的方式插入Null值。
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
补充:python连接数据库插入数据库数据所碰到的坑
Python中插入数据时执行后,没有报任何错误,但数据库中并没有出现新添加的数据
缺少提交操作。
Python操作数据库时,如果对数据表进行修改/删除/添加等控制操作,系统会将操作保存在内存,只有执行commit(),才会将操作提交到数据库。
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')
咋一看好像也有commit呀,怎么一直在数据库没有,再仔细看看
try: self.connection()[1].execute(sql) self.connection()[0].commit() except: self.connection()[0].rollback()
connection()调用方法方法返回的对象是同一个吗?
并不是,心累,搞了半天,只怪自己还太嫩。
try: cons = self.connection() cons[1].execute(sql) cons[0].commit() cons[0].close() except: cons[0].rollback()