Python 如何實(shí)現(xiàn)數(shù)據(jù)庫表結(jié)構(gòu)同步
近日,某個(gè)QQ 群里的一個(gè)朋友提出一個(gè)問題,如何將一個(gè)DB 的表結(jié)構(gòu)同步給另一個(gè)DB。針對(duì)這個(gè)問題,我進(jìn)行了思考與實(shí)踐,具體的實(shí)現(xiàn)代碼如下所示:
# coding:utf-8import pymysqldbDict = {'test1':'l-beta.test1'}dbUser = 'test'dbPassword = '123456'class DBUtils(): def __init__(self): self.conn = pymysql.connect(dbDict[’test1’], dbUser, dbPassword) self.cursor = self.conn.cursor() def dbSelect(self, sql): print('------------------------------------') print(sql) resultList = [] self.cursor.execute(sql) result = self.cursor.fetchall() columns = self.cursor.description for val in result: tempDict = {} for cloNum in range(len(columns)):tempDict[str(columns[cloNum][0])] = val[cloNum] resultList.append(tempDict) print('---------------------打印查詢結(jié)果----------------------') print(resultList) self.dbClose() return resultList def dbExcute(self, sql): print(sql) self.cursor.execute(sql) self.dbClose() def dbClose(self): self.conn.commit() self.cursor.close() self.conn.close()if __name__ == '__main__': test = DBUtils() result = test.dbSelect('select table_name from information_schema.tables where table_schema=’testdb1’') for dict1 in result: test = DBUtils() create_table_sql = 'create table testdb.%s as select * from testdb1.%s' % (dict1[’table_name’],dict1[’table_name’]) print(create_table_sql) test.dbExcute(create_table_sql)
示例代碼操作簡單,通俗易懂,所以沒有過多的注釋,如有疑問的小伙伴們,可在文章下方評(píng)論。
以上就是Python 如何實(shí)現(xiàn)數(shù)據(jù)庫表結(jié)構(gòu)同步的詳細(xì)內(nèi)容,更多關(guān)于Python 數(shù)據(jù)庫表結(jié)構(gòu)同步的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python如何換行輸出2. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼3. Python:UserWarning:此模式具有匹配組。要實(shí)際獲得組,請(qǐng)使用str.extract4. 解決Android Studio 格式化 Format代碼快捷鍵問題5. Java使用Tesseract-Ocr識(shí)別數(shù)字6. python如何計(jì)算圓的面積7. 詳解java google Thumbnails 圖片處理8. Vue實(shí)現(xiàn)聊天界面9. Android Studio中一套代碼多渠道打包的實(shí)現(xiàn)方法10. Android打包篇:Android Studio將代碼打包成jar包教程
