python mysql数据库插入timestamp
阅读原文时间:2021年04月20日阅读:1

利用python向mysql数据库插入timestamp

def insert_install_service_info(serviceName,nodeID,nodeIP='9.42.83.54'):
    conn = MySQLdb.connect(host='172.17.46.15',user='root',passwd='huxin2010')
    curs = conn.cursor()
    serviceNode = {}
    try:
        conn.select_db('nodeInfo')
    except Exception:
        logger.error("the database you find does not exist!")
    try:
        sql = "insert into service3 values('NULL',%s,%s,%s,%s)"
        now = datetime.datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M:%S")
        values = [serviceName,nodeID,nodeIP,now]
        curs.execute(sql,values)
    except Exception:
        logger.error("error: insert data fail")
    conn.commit()
    curs.close()
    conn.close()

数据表定义如下:

mysql> describe service3;
+-------------+-------------+------+-----+---------------------+----------------+
| Field       | Type        | Null | Key | Default             | Extra          |
+-------------+-------------+------+-----+---------------------+----------------+
| id          | int(4)      | NO   | PRI | NULL                | auto_increment |
| serviceName | varchar(20) | NO   |     | NULL                |                |
| nodeID      | int(4)      | NO   |     | NULL                |                |
| nodeIP      | varchar(20) | NO   |     | NULL                |                |
| time        | timestamp   | NO   |     | 0000-00-00 00:00:00 |                |
+-------------+-------------+------+-----+---------------------+----------------+
5 rows in set (0.26 sec)