首页 > 代码库 > 记录一段python代码 (修改数据库字符串)

记录一段python代码 (修改数据库字符串)

 场景:由于开发恶心的账号登录设置,鉴于日本玩家用户习惯,刚开始以游客的身份登录游戏,若发生换包或者换设备,都需要从数据库重新更换账号ID,刚开始纯手工,其后py实现,封装为exe直接在dos里面执行,最好的方式改进当然是在web见面一键完成,现将代码跑路,作为记录。



# coding=utf-8
import pymysql
import traceback
import simplejson
import sys
# 交换
def exchange(connect_index, file_name):
    try:
        # 读取数据库配置
        fp = open("config.json")
        connect_info = simplejson.load(fp)["db_list"]
        fp.close()
        # 创建链接
        conn = pymysql.connect(host=str(connect_info[connect_index]["ip"]),
                               port=int(connect_info[connect_index]["port"]),
                               user=str(connect_info[connect_index]["user"]),
                               passwd=str(connect_info[connect_index]["passwd"]),
                               db=str(connect_info[connect_index]["db_name"]),
                               charset=‘utf8‘)
        # 获取光标
        cur = conn.cursor()
        # 读取交换列表
        fp = open(str(file_name))
        exchange_data = simplejson.load(fp)
        fp.close()
        # 开始交换
        for item in exchange_data:
            # 读取两个值的account_id
            player_datas = []
            for i in range(2):
                temp_data = {}
                cur.execute("select `id`, `account_id` from `character` where `"
                            + str(item["key"][i])
                            + "` = ‘"
                            + str(item["value"][i]) + "‘")
                result = cur.fetchall()
                temp_data["id"] = result[0][0]
                temp_data["account_id"] = result[0][1]
                player_datas.append(temp_data)
            # 更改account_id以免发生冲突
            for player_data in player_datas:
                cur.execute("update `character` set `account_id` = ‘" + str(
                    player_data["account_id"]) + "_‘ where `id` = ‘" + str(player_data["id"]) + "‘")
            conn.commit()
            # 交换
            temp_data = player_datas[0]["account_id"]
            player_datas[0]["account_id"] = player_datas[1]["account_id"]
            player_datas[1]["account_id"] = temp_data
            for player_data in player_datas:
                cur.execute("update `character` set `account_id` = ‘" + str(
                    player_data["account_id"]) + "‘ where `id` = ‘" + str(player_data["id"]) + "‘")
            conn.commit()
        conn.close()
    except Exception:
        traceback.print_exc()
if __name__ == ‘__main__‘:
    try:
        if len(sys.argv) < 3:
            print "arg error"
            sys.exit(1)
        exchange(int(sys.argv[1]), sys.argv[2])
    except Exception:
        traceback.print_exc()



 部分json文件 还未整理,若有疑问请问博主,反正他也不会告诉你。

本文出自 “江湖笑笑生” 博客,请务必保留此出处http://hashlinux.blog.51cto.com/9647696/1913550

记录一段python代码 (修改数据库字符串)