【python-sql】sql操作时遇到的坑

针对python的sql语句的封装以及调用:

python的db操作类:

# -*- coding: utf-8 -*-
# coding=utf-8

import MySQLdb

class Database(object):
    
    [_db_handler, _cursor] = (None, None)
    def __init__(self, host=HOST, port=PORT, user='user', passwd='passwd', db_name='mydb'):
        try:
            self._db_handler = MySQLdb.connect(host, user, passwd, db_name)
            self._cursor = self._db_handler.cursor()
        except Exception, e:
            print e
        
    def query(self, table, condition=None, column='*',log=""):
            try:
                cmd = 'SELECT %s from %s ' % (column, table)
                if condition:
                    cmd = cmd + "WHERE %s" % condition
                cmd = cmd + ';'
                log.info(cmd)
                self._cursor.execute('set NAMES utf8')
                self._cursor.execute(cmd)
                resultset = self._cursor.fetchall()
                rowcount = self._cursor.rowcount
                return [resultset, rowcount]
            except:
                log.error("Error: unable to fecth data") 
                
    def execute(self, command, parameters,log):
            try:
                cmd = command % parameters
                cmd = cmd + ';'
                log.info(cmd)
                self._cursor.execute('set NAMES utf8')
                rowcount = self._cursor.execute(cmd)
                self._db_handler.commit()
                return rowcount
            except Exception, e:
                log.error('error:%s' % str(e))
                log.error('execute db error,rollback')
                self._cursor.rollback()
                
    def batchMysqlOpr(self, sqldata, rsdb):
        try:
            for item in range(len(sqldata)):
                    rs = self.query(sqldata[item][1], sqldata[item][2], column=sqldata[item][3])
                    rsdb.setdefault(sqldata[item][0], rs)
        except Exception, e:
            print e
            return
                 
    def singleMysqlOpr(self,key,command,paramters,rsdb):
        try:
            rowcount = self.execute(command, paramters)
            if key:
                rsdb.setdefault(key, rowcount)  
            return rowcount
        except Exception, e:
            print e
            return

if __name__ == '__main__':
    pass

通过以上代码进行具体操作的时候,比如insert操作,如果我的表中第一个字段是自增的,需要insert into biao(ziduan1, ziduan2, ziduan3) values(value1, value2, value3) ,把具体字段写清楚,而不能直接通过insert into biao values(ziduan1, ziduan2, ziduan3)的这种方式来调用

并且,在调用的时候,如果插入的内容是string类型的,则sql的命令需要按照:

sql_command = 'insert into a (ziduan1, ziduan2, ziduan3) values("%s", "%s", "%s")'    

#注意sql的命令行语句本身就是str型的,通过''括起来的,values里面的%s就需要通过""双引号括起来,如果外面是双引号,则里面的%s就写成单引号,能区分开就可以

parameters = (string_bianliang1, stringbianliang2, string_bianliang3)

之后进行db.execute(sql_command, paramters),才可以正常运行

这里已经踩过坑了,一定要注意~~~

原文地址:https://www.cnblogs.com/keke-xiaoxiami/p/6486314.html