python 数据库的方法封装
#coding:utf-8 import MySQLdb def get_mysql_data(sql,data=None): ''' sql: sql语句 select开头,查询单条语句 SELECT开头,查询多条语句 配置文件里要提前定义一个字典,字典内容如下 MySQL_CONFIG = { 'HOST':'xxxxxxx',#数据库ip地址 "PORT" : 3306,#端口号 "USER" :'xxxxxxx',#用户 "PASSWORD": 'xxxxxxx',#密码 "DB" : 'xxxxxxx'#数据库 } ''' try: #捕捉mysql连接异常 conn = MySQLdb.connect(host=MySQL_CONFIG['HOST'], port=MySQL_CONFIG['PORT'], user=MySQL_CONFIG['USER'], passwd=MySQL_CONFIG['PASSWORD'], db=MySQL_CONFIG['DB'], charset='utf8' ) except Exception as e: print('mysql连接失败'),e else: cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) #创建游标 try: #捕捉sql错误异常 cursor.execute(sql,data)#这样执行sql是为了防止sql注入 except Exception as e: print('sql执行失败,请检查sql!') return 'sql_error' else: conn.commit() #如果sql执行成功的话,提交一下 if sql[:6]=='select':#如果是select语句,读取单条数据 return cursor.fetchone() elif sql[:6]=='SELECT': #如果是SELECT语句,读取全部数据 return cursor.fetchall() else: return cursor.lastrowid#如果不是select语句的话,返回自增长id finally:#不管sql执行成功没执行成功,都关闭连接 cursor.close() conn.close()