因為工作需要,項目以前使用的mysql數據,現在需要更改為postgresql。
一、MYSQL轉PG
1.1 同步表結構
利用navicat:工具->數據傳輸直接將mysql庫->postgresql庫,變動:
- navicat轉換后的sql,會丟失默認值
官網找到一個工具Mysql轉PostgreSQL,這個工具官方是付費的,貌似是專門做異構數據庫轉換的。限制是單表只能轉50條數據,表無限制。
1.2 同步數據
使用navicat:工具->數據傳輸直接將數據從mysql同步到pg即可。
二、DDL變動
2.1 修改列
MYSQL:
ALTER TABLE table_name MODIFY COLUMN column_name datatype
pg:
ALTER TABLE table_name ALTER COLUMN column_name TYPE datatype
2.2 類型變動
mysql->pg:
tinyint->int
datetime->timestamp
三、DML變動
3.1 SQL查詢類型相關
postgresql string的列不能用integer的值查,mysql可以自動轉;
3.2 PG查詢語句不區分大小寫
數據表中字段如果有大寫的話,pg查詢語句是需要加雙引號的,因此創建數據表的時候字段最好采用下划線的方式:
select id,"loginName" from user;
3.3 PostgreSQL與MySQL的日期類型DATE/date的格式區別
參考;PostgreSQL與MySQL的日期類型DATE/date的格式區別
更多sql實現和標准sql區別可以查看https://www.runoob.com/sql/sql-tutorial.html。
四、如何將mysql列名從駝峰修改為下划線
由於歷史原因,在創建數據表的時候,表字段采用了駝峰命名,如何將命名規則轉為帶有下划線的呢?
4.1 mysql查詢所有列名
我們可以通過如下命令查詢一個數據庫下有哪些字段:
select * from information_schema.columns where table_schema='blog'
結果如下:
4.2 編寫批量修改腳本
我們可以編寫python腳本,根據表名、舊的字段名,屬性信息,以及新的列名,然后生成批量修改列名的腳本。每一條修改語句類似:
ALTER TABLE `table_name` CHANGE `$old_column_name` `new_column_name` VARCHAR(40) null default "xxx" comment "comment"
需要注意的是:
該條語句不會更改原有的索引。
python腳本如下:
import pymysql class MySqlTransform(object): """ 將mysql數據庫auth庫中的所有表中駝峰格式的字段轉為下划線命名 """ def __init__(self, host, port, user, password,database): # 數據庫配置 self.__conn = None self.__MYSQL_CONFIG = { 'user': user, 'port': port, 'host': host, 'password': password, 'database': database } self.__cur = self.__get_connect() def __get_connect(self): # 建立連接 self.__conn = pymysql.connect(**self.__MYSQL_CONFIG) # 使用cursor()方法獲取操作游標 cur = self.__conn.cursor() if not cur: raise (NameError, "連接數據庫失敗") else: return cur def __del__(self): """ 析構 """ if self.__conn: self.__conn.close() def exec_query(self, sql): """ 執行查詢語句 """ self.__cur.execute(sql) return self.__cur # 駝峰轉下划線 ID=>id loginName => login_name def camel_to_underline(text): lst = [] last_supper_index = None for index, char in enumerate(text): if char.isupper(): if index != 0 and (last_supper_index == None or last_supper_index + 1 != index): lst.append("_") last_supper_index = index lst.append(char) return "".join(lst).lower() def transform_sql_column(item=None): database = "blog" sql = "select * from information_schema.columns where table_schema='{}';".format(database) mysql = MySqlTransform("127.0.0.1", 3306, "root", "123456",database) cur = mysql.exec_query(sql) res = cur.fetchall() for index, item in enumerate(res): table_name = item[2] old_column_name = item[3] new_column_name = camel_to_underline(old_column_name) column_type = item[15] column_null = 'null' if item[6] == 'YES' else 'not null' column_defult = '' if item[5] is None else 'default {}'.format(item[5]) column_comment = item[19] if old_column_name == new_column_name: continue # 分割 sql = 'alter table {} change column {} {} {} {} {} comment "{}";'.format(table_name,old_column_name,new_column_name, column_type, column_null, column_defult, column_comment) print(sql) if __name__ == '__main__': transform_sql_column()
輸出結果如下:
"D:\Program Files\python\python.exe" E:/個人學習代碼/python/sql/mysql_main.py alter table t_blog_article change column viewCount view_count int null default 0 comment ""; alter table t_blog_article change column createdAt created_at datetime null comment ""; alter table t_blog_article change column updatedAt updated_at datetime null comment ""; alter table t_blog_category change column articleId article_id int null comment ""; alter table t_blog_comment change column articleId article_id int null comment ""; alter table t_blog_comment change column createdAt created_at datetime null comment ""; alter table t_blog_comment change column updatedAt updated_at datetime null comment ""; alter table t_blog_comment change column userId user_id int null comment ""; alter table t_blog_ip change column userId user_id int null comment ""; alter table t_blog_privilege change column privilegeCode privilege_code varchar(32) not null comment "權限code"; alter table t_blog_privilege change column privilegeName privilege_name varchar(32) null comment "權限名"; alter table t_blog_reply change column createdAt created_at datetime null comment ""; alter table t_blog_reply change column updatedAt updated_at datetime null comment ""; alter table t_blog_reply change column articleId article_id int null comment ""; alter table t_blog_reply change column commentId comment_id int null comment ""; alter table t_blog_reply change column userId user_id int null comment ""; alter table t_blog_request_path_privilege_mapping change column urlId url_id int null comment "請求路徑id"; alter table t_blog_request_path_privilege_mapping change column privilegeId privilege_id int null comment "權限id"; alter table t_blog_role change column roleName role_name varchar(32) not null comment "角色名"; alter table t_blog_role_privilege_mapping change column roleId role_id int not null comment "角色id"; alter table t_blog_role_privilege_mapping change column privilegeId privilege_id int not null comment "權限id"; alter table t_blog_tag change column articleId article_id int null comment ""; alter table t_blog_user change column disabledDiscuss disabled_discuss tinyint(1) not null default 0 comment "禁言:0不禁言,1禁言"; alter table t_blog_user change column createdAt created_at datetime null comment ""; alter table t_blog_user change column updatedAt updated_at datetime null comment ""; alter table t_blog_user_role_mapping change column userId user_id int not null comment "用戶id"; alter table t_blog_user_role_mapping change column roleId role_id int not null comment "角色id"; Process finished with exit code 0