自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何利用Python實(shí)現(xiàn)SQL自動(dòng)化?

開發(fā) 后端 自動(dòng)化
筆者在工作中經(jīng)常要使用SQL,其不乏存在惱人的細(xì)微差異和種種限制,但說(shuō)到底,它是數(shù)據(jù)行業(yè)的基石。因此,對(duì)于每一位數(shù)據(jù)領(lǐng)域的工作者,SQL都是不可或缺的。精通SQL意義非凡。

 筆者在工作中經(jīng)常要使用SQL,其不乏存在惱人的細(xì)微差異和種種限制,但說(shuō)到底,它是數(shù)據(jù)行業(yè)的基石。因此,對(duì)于每一位數(shù)據(jù)領(lǐng)域的工作者,SQL都是不可或缺的。精通SQL意義非凡。

[[319027]]

SQL是很不錯(cuò),但怎么能僅滿足于“不錯(cuò)”呢?為什么不進(jìn)一步操作SQL呢?

陳述性語(yǔ)句會(huì)誘發(fā)SQL限制的發(fā)生,就是說(shuō),向SQL尋求數(shù)據(jù),SQL會(huì)在特定數(shù)據(jù)庫(kù)找尋并反饋。對(duì)于許多數(shù)據(jù)提取或簡(jiǎn)單的數(shù)據(jù)操作任務(wù)來(lái)說(shuō),這已經(jīng)足夠了。

但如果有更多需求怎么辦?

本文將為你展示如何操作。

 

從基礎(chǔ)開始

 

  1. import pyodbc 
  2. from datetime import datetime 
  3. classSql: 
  4.     def__init__(self,  database, server="XXVIR00012,55000"): 
  5.         # here we are  telling python what to connect to (our SQL Server) 
  6.         self.cnxn = pyodbc.connect("Driver={SQL  Server Native Client 11.0};" 
  7.                                    "Server="+server+";" 
  8.                                    "Database="+database+";" 
  9.                                    "Trusted_Connection=yes;"
  10.         # initialise  query attribute 
  11.         self.query ="--  {}\n\n-- Made in Python".format(datetime.now() 
  12.                                                           .strftime("%d/%m/%Y")) 

這個(gè)代碼就是操作MS SQL服務(wù)器的基礎(chǔ)。只要編寫好這個(gè)代碼,通過(guò)Python 連接到SQL 僅需:

 

  1. sql = Sql('database123'

很簡(jiǎn)單對(duì)么?同時(shí)發(fā)生了幾件事,下面將對(duì)此代碼進(jìn)行剖析。class Sql:

首先要注意,這個(gè)代碼包含在一個(gè)類中。筆者發(fā)現(xiàn)這是合乎邏輯的,因?yàn)樵诖烁袷街?,已?jīng)對(duì)此特定數(shù)據(jù)庫(kù)進(jìn)行了增添或移除進(jìn)程。若見其工作過(guò)程,思路便能更加清晰。

初始化類:

 

  1. def __init__(self, database,server="XXVIR00012,55000"): 

因?yàn)楣P者和同事幾乎總是連接到相同的服務(wù)器,所以筆者將這個(gè)通用瀏覽器的名稱設(shè)為默認(rèn)參數(shù)server。

在“Connect to Server”對(duì)話框或者M(jìn)S SQL Server Management Studio的視窗頂端可以找到服務(wù)器的名稱:

 

如何利用Python實(shí)現(xiàn)SQL自動(dòng)化?

 

下一步,連接SQL:

 

  1. self.cnxn =pyodbc.connect("Driver={SQL Server Native Client 11.0};" 
  2.                           "Server="+self.server+";" 
  3.                           "Database="+self.database+";" 
  4.                           "Trusted_Connection=yes;"

pyodbc 模塊,使得這一步驟異常簡(jiǎn)單。只需將連接字符串過(guò)渡到 pyodbc.connect(...) 函數(shù)即可,點(diǎn)擊以了解詳情here。

最后,筆者通常會(huì)在 Sql 類中編寫一個(gè)查詢字符串,sql類會(huì)隨每個(gè)傳遞給類的查詢而更新:

 

  1. self.query = "-- {}\n\n--Made in Python".format(datetime.now() 
  2.                                              .strftime("%d/%m/%Y")) 

這樣便于記錄代碼,同時(shí)也使輸出更為可讀,讓他人讀起來(lái)更舒服。

請(qǐng)注意在下列的代碼片段中,筆者將不再更新代碼中的self.query 部分。

 

組塊

一些重要函數(shù)非常有用,筆者幾乎每天都會(huì)使用。這些函數(shù)都側(cè)重于將數(shù)據(jù)從數(shù)據(jù)庫(kù)中傳入或傳出。

以下圖文件目錄為始:

 

如何利用Python實(shí)現(xiàn)SQL自動(dòng)化?

 

對(duì)于當(dāng)前此項(xiàng)目,需要:

  • 將文件導(dǎo)入SQL
  • 將其合并到單一表格內(nèi)
  • 根據(jù)列中類別靈活創(chuàng)建多個(gè)表格

SQL類不斷被充實(shí)后,后續(xù)會(huì)容易很多:

 

  1. import sys 
  2. sys.path.insert(0, r'C:\\User\medium\pysqlplus\lib'
  3. import os 
  4. from data importSql 
  5. sql =Sql('database123')  # initialise the Sql object 
  6. directory =r'C:\\User\medium\data\\'  # this is where our generic data is  stored 
  7. file_list = os.listdir(directory)  # get a list of all files 
  8. for file in  file_list:  # loop to import  files to sql 
  9.     df = pd.read_csv(directory+file)  # read file to dataframe 
  10.     sql.push_dataframe(df, file[:-4]) 
  11. # now we  convert our file_list names into the table names we have imported to SQL 
  12. table_names = [x[:-4] for x in file_list] 
  13. sql.union(table_names, 'generic_jan')  # union our files into one new table  called 'generic_jan' 
  14. sql.drop(table_names)  # drop our original tables as we now  have full table 
  15. # get list of  categories in colX, eg ['hr''finance''tech''c_suite'
  16. sets =list(sql.manual("SELECT  colX AS 'category' FROM generic_jan GROUP BY colX", response=True)['category']) 
  17. for category in sets: 
  18.     sql.manual("SELECT *  INTO generic_jan_"+category+" FROM  generic_jan WHERE colX = '"+category+"'"

從頭開始。

入棧數(shù)據(jù)結(jié)構(gòu)

 

  1. defpush_dataframe(self, data,  table="raw_data", batchsize=500): 
  2.     # create execution cursor 
  3.     cursor = self.cnxn.cursor() 
  4.     # activate fast execute 
  5.     cursor.fast_executemany =True 
  6.     # create create table statement 
  7.     query ="CREATE  TABLE ["table +"] (\n" 
  8.     # iterate through each column to be  included in create table statement 
  9.     for i inrange(len(list(data))): 
  10.         query +="\t[{}]  varchar(255)".format(list(data)[i])  # add column (everything is varchar  for now) 
  11.         # append correct  connection/end statement code 
  12.         if i !=len(list(data))-1: 
  13.             query +=",\n" 
  14.         else
  15.             query +="\n);" 
  16.     cursor.execute(query)  # execute the create table statement 
  17.     self.cnxn.commit()  # commit changes 
  18.     # append query to our SQL code logger 
  19.     self.query += ("\n\n--  create table\n"+ query) 
  20.     # insert the data in batches 
  21.     query = ("INSERT  INTO [{}] ({})\n".format(table
  22.                                                '['+'], ['  # get columns 
  23.                                                .join(list(data)) +']') + 
  24.              "VALUES\n(?{})".format(",  ?"*(len(list(data))-1))) 
  25.     # insert data into target table in  batches of 'batchsize' 
  26.     for i inrange(0, len(data), batchsize): 
  27.         if i+batchsize >len(data): 
  28.             batch = data[i: len(data)].values.tolist() 
  29.         else
  30.             batch = data[i: i+batchsize].values.tolist() 
  31.         # execute batch  insert 
  32.         cursor.executemany(query, batch) 
  33.         # commit insert  to SQL Server 
  34.         self.cnxn.commit() 

此函數(shù)包含在SQL類中,能輕松將Pandas dataframe插入SQL數(shù)據(jù)庫(kù)。

其在需要上傳大量文件時(shí)非常有用。然而,Python能將數(shù)據(jù)插入到SQL的真正原因在于其靈活性。

要橫跨一打Excel工作簿才能在SQL中插入特定標(biāo)簽真的很糟心。但有Python在,小菜一碟。如今已經(jīng)構(gòu)建起了一個(gè)可以使用Python讀取標(biāo)簽的函數(shù),還能將標(biāo)簽插入到SQL中。

Manual(函數(shù))

 

  1. defmanual(self, query,  response=False): 
  2.     cursor = self.cnxn.cursor()  # create execution cursor 
  3.     if response: 
  4.         returnread_sql(query,  self.cnxn)  # get sql query  output to dataframe 
  5.     try: 
  6.         cursor.execute(query)  # execute 
  7.     except pyodbc.ProgrammingErroras error: 
  8.         print("Warning:\n{}".format(error))  # print error as a warning 
  9.     self.cnxn.commit()  # commit query to SQL Server 
  10.     return"Query  complete." 

此函數(shù)實(shí)際上應(yīng)用在union 和 drop 函數(shù)中。僅能使處理SQL代碼變得盡可能簡(jiǎn)單。

response參數(shù)能將查詢輸出解壓到DataFrame。generic_jan 表中的colX ,可供摘錄所有獨(dú)特值,操作如下:

 

  1. sets =list(sql.manual("SELECT colX AS 'category' FROM generic_jan GROUP BYcolX", response=True)['category']) 

Union(函數(shù))

構(gòu)建 了manual 函數(shù),創(chuàng)建 union 函數(shù)就簡(jiǎn)單了:

 

  1. defunion(self,  table_list, name="union"join="UNION"): 
  2.     # initialise the query 
  3.     query ="SELECT *  INTO ["+name+"] FROM (\n" 
  4.     # build the SQL query 
  5.     query +=f'\n{join}\n'.join
  6.                         [f'SELECT [{x}].* FROM [{x}]'for x in table_list] 
  7.                         ) 
  8.     query +=")  x"  # add end of  query 
  9.     self.manual(query, fast=True)  # fast execute 

創(chuàng)建 union 函數(shù)只不過(guò)是在循環(huán)參考 table_list提出的表名,從而為給定的表名構(gòu)建 UNION函數(shù)查詢。然后用self.manual(query)處理。

Drop(函數(shù))

上傳大量表到SQL服務(wù)器是可行的。雖然可行,但會(huì)使數(shù)據(jù)庫(kù)迅速過(guò)載。 為解決這一問題,需要?jiǎng)?chuàng)建一個(gè)drop函數(shù):

 

  1. defdrop(self,  tables): 
  2.     # check if single or list 
  3.     ifisinstance(tables, str): 
  4.         # if single  string, convert to single item in list for for-loop 
  5.         tables = [tables] 
  6.     for table in tables: 
  7.         # check for  pre-existing table and delete if present 
  8.         query = ("IF  OBJECT_ID ('["+table+"]', 'U')  IS NOT NULL " 
  9.                  "DROP TABLE  ["+table+"]"
  10.         self.manual(query)  # execute 

view rawpysqlplus_drop_short.py hosted with ❤ by GitHub

點(diǎn)擊

https://gist.github.com/jamescalam/b316c1714c30986fff58c22b00395cc0

得全圖

同樣,此函數(shù)也由于 manual 函數(shù)極為簡(jiǎn)單。操作者可選擇輸入字符到tables ,刪除單個(gè)表,或者向tables提供一列表名,刪除多個(gè)表。

當(dāng)這些非常簡(jiǎn)單的函數(shù)結(jié)合在一起時(shí),便可以利用Python的優(yōu)勢(shì)極大豐富SQL的功能。

筆者本人幾乎天天使用此法,其簡(jiǎn)單且十分有效。

希望能夠幫助其他用戶找到將Python并入其SQL路徑的方法,感謝閱讀!

責(zé)任編輯:華軒 來(lái)源: 今日頭條
相關(guān)推薦

2024-04-30 08:00:00

人工智能自動(dòng)化文件處理

2017-12-17 21:58:18

2010-09-27 09:13:36

Visual Stud

2009-04-16 17:14:52

2021-11-01 10:26:08

傳感器農(nóng)業(yè)自動(dòng)化物聯(lián)網(wǎng)

2011-01-20 10:17:25

ibmdwWeb

2011-09-29 10:58:51

rBuilderLinux

2024-06-11 10:41:14

2018-08-31 09:55:38

Ansible網(wǎng)絡(luò)自動(dòng)化

2018-01-30 10:24:41

2017-07-21 09:14:21

2010-03-03 16:36:02

Python PAMI

2018-05-10 15:54:39

2021-01-28 10:28:33

云計(jì)算基礎(chǔ)設(shè)施自動(dòng)化IT

2020-05-25 14:32:42

Python電子郵件自動(dòng)化

2021-11-02 09:00:00

物聯(lián)網(wǎng)人工智能自動(dòng)化

2023-12-18 15:26:56

物聯(lián)網(wǎng)

2024-03-25 08:00:00

人工智能

2024-01-09 13:09:00

2024-11-21 15:24:49

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)