2016-12-22 11 views
0

nameのテーブルはvarchar(50)ctimedatetimeです。 私がMySQL insert into atable (name, ctime) values ('aname', NULL)で実行すると動作します。パイソン3においてPython 3 pymysql insert with datetimeフィールド

Iは、以下の方法(すべての生成エラー)を試みた:

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()