標籤:多表 恢複 工具 art 欄位名 刪除 doc str 2.7
這是我之前使用mysql時用到的一些庫及開發的工具,這裡記錄下,也方便我查閱。
python版本: 2.7.13
mysql版本: 5.5.36
幾個python庫
1、mysql-connector-python
是MySQL官方的Python驅動
https://dev.mysql.com/doc/connector-python/en/
安裝:
pip install mysql-connector
範例程式碼:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/mysql-connector_Opt/test1.py
2、MySQL-python
是封裝了MySQL C驅動的Python驅動。
安裝:
pip install MySQL
CentOS下:yum install MySQL-python
範例程式碼:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/MySQLdb_Opt/test1.py
3、pymysql
純python實現的mysql庫
安裝:
pip install PyMySQL
範例程式碼:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/pymysql_Opt/test1.py
幾個工具
以下幾個工具均使用MySQL-python庫開發,需要提前安裝該庫。
1、將mysql表中的資料備份到csv檔案
mysqldump可以備份資料,但備份的是sql語句,有時候需要將單筆或多表備份為csv檔案時,該工具適用。
原理:
分頁擷取資料並將資料寫入到csv檔案
源碼地址:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/MySQLdb_Opt/csvBakAndRestore/backTable2csv_test1.py
2、從csv檔案匯入資料到mysql表
和資料匯出對應,帶有表頭的csv檔案需要匯入資料庫時,該工具適用。
原理:
讀取csv檔案並產生sql語句,批量提交語句入庫。
源碼地址:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/MySQLdb_Opt/csvBakAndRestore/restoreTableFromCSV_test1.py
3、從sql檔案匯入資料到mysql表
匯出的sql檔案需要恢複時,如果檔案過大,會出現等待時間很長的問題,在這段時間內資料無法查看,如果要解決這個問題,該工具適用。
原理:
讀取sql語句,分批次提交(預設10000條提交一次)
源碼地址:
https://github.com/mike-zhang/pyExamples/tree/master/databaseRelate/mysqlOpt/MySQLdb_Opt/importFromSqlString
4、擷取建表語句
有批量擷取mysql建表語句的需求,該工具適用。
原理:
通過 show tables 擷取資料庫中的表名稱列表,然後通過 show create table 擷取建表語句。
源碼地址:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/MySQLdb_Opt/getTableCreateSql.py
5、擷取表欄位名稱
有擷取表欄位名的需求,該工具適用。
原理:
通過 desc 命令擷取表欄位資訊
源碼地址:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/MySQLdb_Opt/getTableFields.py
6、分頁測試
資料過多,需要分頁擷取時,該代碼適用。
原理:
通過limit實現
源碼地址:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/MySQLdb_Opt/pagingTest1.py
7、批量清理表內容
需要批量清理表的內容時,該代碼適用。
原理:
通過指令碼執行多條刪除語句。
源碼地址:
https://github.com/mike-zhang/pyExamples/blob/master/databaseRelate/mysqlOpt/MySQLdb_Opt/clearTables.py
好,就這些了,希望對你有協助。
本文github地址:
https://github.com/mike-zhang/mikeBlogEssays/blob/master/2017/20170703_使用python操作mysql資料庫.rst
歡迎補充
使用python操作mysql資料庫