Last active
October 19, 2018 08:29
-
-
Save ayuLiao/56ee8d2a0a23af7e068fb8ab649bad24 to your computer and use it in GitHub Desktop.
公司旧项目使用python2,其独特的编码问题,给操作mysql时带来了些小问题
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def initMySQL(): | |
''' | |
链接mysql | |
:return: | |
''' | |
mysql_options = dict( | |
host="127.0.0.1", | |
db="数据表名称", | |
port=3306, | |
user="账号", | |
passwd='MySQL密码', | |
use_unicode=1, | |
charset="utf8" #将链接编码设置成UTF-8才能往mysql中插入中文数据 | |
) | |
db = MySQLdb.connect(**mysql_options) | |
return db #返回mysql游标 | |
def isExist(db, tablename): | |
''' | |
判断表是否存在 | |
''' | |
sql = 'show tables' | |
con = self.db_con.cursor() | |
con.execute(sql) | |
tables = [con.fetchall()] | |
table_list = re.findall('(\'.*?\')', str(tables)) | |
table_list = [re.sub("'", '', each) for each in table_list] | |
if tablename in table_list: | |
return True | |
else: | |
return False | |
def initTable(db,tablename,sql): | |
''' | |
创建数据表 | |
:param db: MySQL链接 | |
:return: | |
''' | |
res = isExist(db,tablename) | |
if res:#已经存在 | |
return True | |
cursor = db.cursor() | |
cursor.execute(sql) | |
return True | |
def hasDataInTable(db,tablename): | |
''' | |
mysql相应的表中是否有数据 | |
:param db: | |
:return: True有,False没有 | |
''' | |
cursor = db.cursor() | |
sql = '''SELECT id FROM `{tablename}` limit 0,1'''.format(tablename=tablename) | |
cursor.execute(sql) | |
res = cursor.fetchall() | |
if not res: #没数据,需要将目前Redis中的所有数据存入MySQL | |
return False | |
return True | |
def insertDataInMySQL(db,tablename, sql): | |
''' | |
将数据插入表汇总 | |
:param db:数据库连接 | |
:param tablename:表名 | |
:return: | |
''' | |
cursor = db.cursor() | |
try: | |
cursor.execute(sql) | |
db.commit() | |
except: | |
db.rollback() | |
def closeMySQL(db): | |
''' | |
关闭mysql链接 | |
:param db:MySQL链接 | |
:return: | |
''' | |
db.close() | |
## 插入语句 | |
tablename = 'tablename' | |
owneruserid = 1 | |
gamename = '游戏名字' | |
datatime = '2018-02-02' | |
sideusers = "[{'1':'2'}]" #游戏用户,json格式 | |
roomid = 1 | |
gameid = 1 | |
add_time = '2018-03-23' | |
# 中文,json格式,都要加上 '',不然SQL执行会报错 | |
sql = "INSERT INTO %s(ownneruserid,gamenatame,datatime,sideusers,roomid,gameid,add_time) VALUES (%d,'%s','%s','%s',%d,%d,'%s')"%(tablename,ownneruserid,gamename, datatime,sideusers,roomid,gameid, add_time) | |
insertDataInMySQL(db,TABLENAME1,sql) | |
sql = 'INSERT INTO %s(userid,operate_id,datatime,roomcard_changenum,\ | |
roomcard_num,add_time) VALUES (%d,%d,\'%s\',%d,%d,\'%s\')' % (tablename, | |
userid, operate_id, datatime, roomcard_changenum, roomcard_num, add_time) | |
insertDataInMySQL(db, TABLENAME1, sql) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment