1. 程式人生 > 其它 >python報表自動化系列 - 通過Python使用MySQL資料庫

python報表自動化系列 - 通過Python使用MySQL資料庫

技術標籤:pythonpythonmysql

通過Python使用MySQL資料庫例項

李俊才
郵箱:[email protected]

【函式說明】

如呼叫本函式,必須先安裝有MySQL資料庫軟體,並已經建立了某個資料庫,然後方可使用本函式對已經建立好的資料庫建立一個新的表。
[引數]:

  • host:主機名,或者是網路中主機的IP地址,對於本地主機,為’localhost’
  • user:使用者名稱,在生產環境不建議直接使用root使用者
  • password:對於與使用者名稱的密碼;
  • db:已經建立好的某資料庫名;
  • table_name:需要建立的表名;
  • Column_list:列名稱的列表;
  • Datatype_list:所有列的資料型別列表;
  • primary_key:對應SQL的PRIMARY KEY,約束唯一標識資料庫表中的每條記錄。主鍵必須包含唯一的值,主鍵列不能包含 NULL 值,每個表都應該有一個主鍵,並且每個表只能有一個主鍵。

【程式碼實現】

import pymysql
#給指定主機上的某資料庫建立表
def creat_MySQL_table(host, user, password, db, table_name, Column_list, Datatype_list, primary_key):
    connection = pymysql.connect(host =
host, user = user, password = password, db = db, charset = 'utf8', #字元編碼 ) #使用cursor()方法來建立一個遊標物件cuisor cursor = connection.
cursor() SQL_DROP = "DROP TABLE IF EXISTS " + table_name #使用execute()方法執行SQL_DROP,如果表存在則刪除 cursor.execute(SQL_DROP) SQL_CREAT_TABLE = 'EATE TABLE ' + '`' + table_name + '`' + '(' new_list = [] count_i = 0 for i in Column_list: column = '`' + i + '`' + ' ' + Datatype_list[count_i] + ',' new_list.append(column) Column_list = new_list count_i = count_i + 1 #通過字串拼接實現可以用於MySQL執行的SQL語句 SQL_CREAT_TABLE = 'CREATE TABLE ' + '`' + table_name + '`' + ' ' + '(\n' for i in Column_list: SQL_CREAT_TABLE = SQL_CREAT_TABLE + ' ' + i + '\n' SQL_CREAT_TABLE = SQL_CREAT_TABLE + ' ' + 'PRIMARY KEY (' + primary_key + ')' SQL_CREAT_TABLE = SQL_CREAT_TABLE + '\n' + ')ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin ;' #執行建立表語句 cursor.execute(SQL_CREAT_TABLE) #關閉與資料庫的連線 connection.close() #返回值是用來除錯被用於建立表的SQL語句,建議使用print()函式檢視 return str(SQL_CREAT_TABLE)

【呼叫例項】

#定義呼叫引數
Column_list = ['Time','Normal Drop (000)','No Chute Assignment (001)','Recirculation Exceeded (002)',
               'Unknown Piece / Bad Load (003)','Multiple Barcodes (004)','No Sort Instruction (005)',
               'Other Reasons (006)','VCS Timeout (008)','VCS Reject (009)','No Reads (010)',
               'MES Reject (011)','Total']
Datatype_list = ['int(35) NOT NULL AUTO_INCREMENT','int(5) NULL','int(5) NULL','int(5) NULL','int(5) NULL',
             'int(5) NULL','int(5) NULL','int(5) NULL','int(5) NULL','int(5) NULL','int(5) NULL','int(5) NULL',
             'int(5) NULL']
host = 'localhost'
user = 'root'
password = 'root'
db = 'as01'
table_name = 'Thtoughput'
primary_key = 'Time'

#呼叫函式
creat_MySQL_table(host, user, password, db, table_name, Column_list, Datatype_list, primary_key)

開啟資料庫圖形化管理工具Navicat檢視,可以發現在資料庫“as01”(呼叫前已經建立好)中生成了一個表“Throughput”,如圖所示:
在這裡插入圖片描述
開啟該表,如圖:
在這裡插入圖片描述