2016-12-22 37 views
0

我有一個表name作爲varchar(50)ctime作爲datetime。 如果我在MySQL insert into atable (name, ctime) values ('aname', NULL)中執行它的工作。Python 3 pymysql插入空日期時間字段

在Python 3我嘗試以下方法(所有產生錯誤):

conn = pymysql.connect(host='ahost', port=3306, user='auser', passwd='apasswd', db='adb') 

cur = conn.cursor() 

[嘗試1]

cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', '') 

pymysql.err.InternalError: (1292, "Incorrect datetime value: '' for column 'ctime' at row 1") 

[嘗試2]

cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', '') 

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1") 

[嘗試3]

cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', None) 

pymysql.err.InternalError: (1292, "Incorrect datetime value: 'None' for column 'ctime' at row 1") 

[嘗試4]

cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', None) 

pymysql.err.InternalError: (1054, "Unknown column 'None' in 'field list'") 

任何援助將不勝感激。

+0

請修正語法錯誤具體報價和括號。現在,這些嘗試都不應該運行。 – Parfait

回答

0

在這種情況下,您不需要通過ctime,只是您實際設置的值。

sql = "INSERT INTO `atable` (`name`) VALUES (%s)" 
rows = cursor.execute(sql, ('aname2')) 
print("insert:", rows) 

我運行代碼並工作正常,全碼:

import pymysql 

def main(): 
    try: 
     conn = pymysql.connect(
      host='localhost', user='@@', password='##', 
      db='dn_name' 
     ) 
     with conn.cursor() as cursor: 
      sql = "INSERT INTO `atable` (`name`) VALUES (%s)" 
      rows = cursor.execute(sql, ('aname2')) 
      print("insert:", rows) 

    except Exception as e: 
     conn.rollback() 
     raise e 
    else:   
     conn.commit() 
    finally: 
     conn.close() 

if __name__ == '__main__': 
    main()