MYSQL轉SQL Server腳本
# -*- coding:UTF-8 -*-"""mysql腳本導入到sqlserver中去author: zhangbccreate_time: 2017-05-04"""import sysimport timeimport pyodbcreload(sys)sys.setdefaultencoding(UTF-8)def read_sql(filename=inkks_users.sql, res_filename=hj_users.sql): """ 轉換mysql的sql文件,符合sql server格式 :param fliename: 處理前文件名 :param res_filename: 處理後文件名 :return: """ with open(filename, r) as fp: content = fp.read().replace(`, ).replace(r\, ).replace(r, ) open(res_filename, w).write(content)def exec_sql(filename=hj_users.sql): """ 執行SQL SERVER文件 :param filename: sqlserver文件名 :return: """ try: conn = pyodbc.connect(DRIVER={SQL Server}, SERVER=127.0.0.1, DATABASE=xxxxxxxxx, UID=xxx, PWD=xxxxxxxxxx, charset=utf-8) cur = conn.cursor() except pyodbc.DatabaseError, ex: print SQL Server connecting error,reason is:+str(ex) sys.exit() counts = 0 with open(filename, r) as fp: while True: line = fp.readline() if not line: print the items of %d is finished! -- %s % (counts, time.strftime(%Y-%m-%d %H:%M:%S, time.localtime())) break try: cur.execute(u%s % line) conn.commit() counts += 1 except pyodbc.Error: open(res_error.sql, a).write(line) if counts % 100000 == 0: print the items of %d is finished! -- %s % (counts, time.strftime(%Y-%m-%d %H:%M:%S, time.localtime())) cur.close() conn.close()def main(): """ 主函數 :return: """ # 轉換sql腳本 read_sql(res_error.sql, 11.sql) # 執行SQL腳本 # exec_sql()if __name__ == __main__: start_time = time.strftime(%Y-%m-%d %H:%M:%S, time.localtime()) print Beginning ! Begin: + start_time main() end_time = time.strftime(%Y-%m-%d %H:%M:%S, time.localtime()) print
End: + end_time
也許你會利用sqlcmd導入sql腳本,但是從mysql導出的腳本還是會出現問題,例如mysql表出現「」,"\"等欄位值。
推薦閱讀:
※新版本Django在Windows和Linux下的部署
※零編程基礎,如何學習gis專業?
※Python到底有多慢?
※Python標準庫系列之tarfile模塊
※Python入門 文件讀取與寫入
TAG:Python |