python 插入Null值数据到Postgresql的操作

作者:MichaelZhu 时间:2021-11-24 22:39:24 

数据库中最好插入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()

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

来源:https://blog.csdn.net/a5685263/article/details/103242430

标签:python,Null,Postgresql
0
投稿

猜你喜欢

  • 如何决定是否将登录内容保存到Cookie里?

    2009-12-16 18:54:00
  • python爬虫用scrapy获取影片的实例分析

    2023-09-25 09:22:30
  • Python将string转换到float的实例方法

    2023-06-13 07:23:47
  • PDO::commit讲解

    2023-06-14 05:35:45
  • python使用JSON模块进行数据处理(编码解码)

    2024-01-01 21:52:42
  • matplotlib之pyplot模块坐标轴范围设置(autoscale(),xlim(),ylim())

    2022-03-15 09:01:16
  • Python 3.8正式发布,来尝鲜这些新特性吧

    2023-01-30 18:54:16
  • Python线程协作threading.Condition实现过程解析

    2023-07-25 11:15:27
  • 让你一文弄懂Pandas文本数据处理

    2023-07-17 19:12:08
  • 各种JavaScript开发工具比较

    2007-10-23 13:29:00
  • mysql 存储过程 使用小结

    2010-10-25 20:02:00
  • python 读取DICOM头文件的实例

    2021-12-03 19:30:48
  • 用文本+ASP打造新闻发布系统

    2009-02-02 09:31:00
  • Python的Flask框架应用调用Redis队列数据的方法

    2023-04-20 14:14:38
  • 谈谈Python进行验证码识别的一些想法

    2022-09-19 12:50:53
  • python re的findall和finditer的区别详解

    2022-05-19 23:04:33
  • sql server对字段的添加修改删除、以及字段的说明

    2012-01-05 18:50:52
  • 用Python中的字典来处理索引统计的方法

    2022-05-28 19:43:45
  • 蜕变——记QQ医生3.0

    2009-09-16 14:41:00
  • flask框架自定义过滤器示例【markdown文件读取和展示功能】

    2023-03-07 19:22:27
  • asp之家 网络编程 m.aspxhome.com