当前位置 博文首页 > python 插入Null值数据到Postgresql的操作

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

    作者:MichaelZhu 时间:2021-07-16 18:50

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

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

    jsjbwy