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

yipeiwu_com5年前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 

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

相关文章

python按行读取文件并找出其中指定字符串

python按行读取文件并找出其中指定字符串 #coding=utf-8 import os, time, sys, re #reload(sys) #sys.setdefaul...

Python 命令行非阻塞输入的小例子

 随手google咗一下,基本上都用select实现非阻塞监听,但问题是,监听的是用select之后是不能像getchar()那样,即时收到单个字符的输入,必须要等待回车。 &...

python 拷贝特定后缀名文件,并保留原始目录结构的实例

如下所示: #!/usr/bin/python # -*- coding: UTF-8 -*- import os import shutil def cp_tree_ext(ex...

python中@property和property函数常见使用方法示例

本文实例讲述了python中@property和property函数常见使用方法。分享给大家供大家参考,具体如下: 1、基本的@property使用,可以把函数当做属性用 class...

设计模式中的原型模式在Python程序中的应用示例

原型模式: 原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 原型模式本质就是克隆对象,所以在对象初始化操作比较复杂的情况下,很实用,能大大降低耗时,提高性能,因为“不用重...