數據庫中最好插入Null值。
在python中,暫時沒找到通過sql語句的方式插入Null值。
推薦使用輪子的方法
1
2
3
4
5
6
7
8
|
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(),才會將操作提交到數據庫。
但是總有你想不到的坑代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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呀,怎么一直在數據庫沒有,再仔細看看
1
2
3
4
5
|
try : self .connection()[ 1 ].execute(sql) self .connection()[ 0 ].commit() except : self .connection()[ 0 ].rollback() |
connection()調用方法方法返回的對象是同一個嗎?
并不是,心累,搞了半天,只怪自己還太嫩。
正確寫法:
1
2
3
4
5
6
7
|
try : cons = self .connection() cons[ 1 ].execute(sql) cons[ 0 ].commit() cons[ 0 ].close() except : cons[ 0 ].rollback() |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/a5685263/article/details/103242430