解决出现Incorrect integer value: '' for column 'id' at row 1的问题

yipeiwu_com6年前Python基础

解决出现Incorrect integer value: '' for column 'id' at row 1的问题

前言:

今天在学习Python的过程中操作数据库,遇到了一个问题,执行sql语句插入数据的时候报错Incorrect integer value: '' for column 'id' at row 1

我的数据库设计是这样的:

一个很简单的用户信息表,其中ID是int类型,自动填充的主键,其他两个非主键,我执行的insert语句是这样的:mysql.db_insert("insert into userinfo values('','sven','111222','sven@qq.com','1')")

执行的时候一直报错Incorrect integer value: '' for column 'id' at row 1,最后google了一下,发现mysql版本到5以上的都会遇到这样的问题,插入空字符要使用NULL 正确的SQL语句应该是mysql.db_insert("insert into userinfo values(NULL,'sven','111222','sven@qq.com','1')"),记录下来与大家共勉,共通学习。

顺便分享一个自己写的操作数据库的Python类

我的Python数据库编码使用utf-8,所以连接数据库的时候charset这个字段我就没有做处理

# -*- coding: utf-8 -*- 
import MySQLdb 
 
class Mysql: 
  conn = ''  
  cursor = '' 
 
  def __init__(self, host='localhost', usr='blogtest', password='111222', db='blogtest'): 
    try: 
      self.conn = MySQLdb.connect(host, usr, password, db) 
    except Exception, e: 
      print e 
    self.cursor = self.conn.cursor() 
    #self.query('SET NAME %s ' % charset) 
 
 
  def query(self, sql): 
    self.cursor.execute(sql) 
 
  def show(self): 
    return self.cursor.fetchall() 
 
  def db_insert(self,sql): 
    self.cursor.execute(sql) 
    self.conn.commit() 
 
  def __del__(self): 
    self.cursor.close() 
    self.conn.close() 
 
if __name__ == '__main__': 
  mysql = Mysql() 
  mysql.db_insert("insert into userinfo values(NULL,'sven','111222','sven@qq.com','1')") 
  mysql.query('SELECT * FROM userinfo') 
  data = mysql.show() 
  for x in data: 
    print x 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

pandas基于时间序列的固定时间间隔求均值的方法

pandas基于时间序列的固定时间间隔求均值的方法

如果index是时间序列就不用转datetime;但是如果时间序列是表中的某一列,可以把这一列设为index 例如: 代码: DF=df2.set_index(df1['time_...

解决python3 Pycharm上连接数据库时报错的问题

最近在学习python。 今天在学习python连接Mysql数据库时报错: AttributeError: 'NoneType' object has no attribute '...

Pyorch之numpy与torch之间相互转换方式

numpy中的ndarray转化成pytorch中的tensor : torch.from_numpy() pytorch中的tensor转化成numpy中的ndarray : nump...

Python做文本按行去重的实现方法

文本: 每行在promotion后面包含一些数字,如果这些数字是相同的,则认为是相同的行,对于相同的行,只保留一行。 思路: 根据字典和字符串切割。 建立一个空字典。 读入文本,并对每行...

Python退火算法在高次方程的应用

Python退火算法在高次方程的应用

一,简介 退火算法不言而喻,就是钢铁在淬炼过程中失温而成稳定态时的过程,热力学上温度(内能)越高原子态越不稳定,而温度有一个向低温区辐射降温的物理过程,当物质内能不再降低时候该物质原子态...