zoukankan      html  css  js  c++  java
  • python 操作 mysql 数据库 datetime 属性字段为 0000-00-00 00:00:00 的问题

    撇开 sqlalchemy, 先讲 MySQLdb 和 pymysql

    mysql 版本 mysql  Ver 14.14 Distrib 5.1.73

    新建一个测试表 test, 结构如下:

    mysql> desc test;
    +----------+----------+------+-----+---------+-------+
    | Field    | Type     | Null | Key | Default | Extra |
    +----------+----------+------+-----+---------+-------+
    | id       | int(11)  | NO   | PRI | NULL    |       |
    | req_time | datetime | YES  |     | NULL    |       |
    +----------+----------+------+-----+---------+-------+
    2 rows in set (0.00 sec)

    使用 MySQLdb 原生转义

    cursor.execute("insert into test values (%s, %s)", (1, None))

    None 插入后在 mysql 显示为 NULL

    mysql> select * from test;
    +----+----------+
    | id | req_time |
    +----+----------+
    |  1 | NULL     |
    +----+----------+

    如果自己拼接 sql, 就会遇到问题

    cursor.execute("insert into test values (%s, '%s')" % (0, None))

    None 插入后在 mysql 显示为 0000-00-00 00:00:00

    mysql> select * from test;
    +----+---------------------+
    | id | req_time            |
    +----+---------------------+
    |  0 | 0000-00-00 00:00:00 |
    +----+---------------------+

    对于大批量的插入, 可以使用 cursor.executemany, 唯一的缺点就是, sql 语句要写太多的 "%s", 看起来不够美观.

    从各个方面看, sqlalchemy 是最好的选择, 有时间再更新 sqlalchemy 的内容.

  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/senjougahara/p/6361120.html
Copyright © 2011-2022 走看看