如何利用Python实现SQL自动化?( 二 )

从头开始 。
 
入栈数据结构
 
defpush_dataframe(self, data,table="raw_data", batchsize=500):# create execution cursorcursor = self.cnxn.cursor()# activate fast executecursor.fast_executemany =True# create create table statementquery ="CREATETABLE ["+ table +"] (n"# iterate through each column to beincluded in create table statementfor i inrange(len(list(data))):query +="t[{}]varchar(255)".format(list(data)[i])# add column (everything is varcharfor now)# Append correctconnection/end statement codeif i !=len(list(data))-1:query +=",n"else:query +="n);"cursor.execute(query)# execute the create table statementself.cnxn.commit()# commit changes# append query to our SQL code loggerself.query += ("nn--create tablen"+ query)# insert the data in batchesquery = ("INSERTINTO [{}] ({})n".format(table,'['+'], ['# get columns.join(list(data)) +']') +"VALUESn(?{})".format(",?"*(len(list(data))-1)))# insert data into target table inbatches of 'batchsize'for i inrange(0, len(data), batchsize):if i+batchsize >len(data):batch = data[i: len(data)].values.tolist()else:batch = data[i: i+batchsize].values.tolist()# execute batchinsertcursor.executemany(query, batch)# commit insertto SQL Serverself.cnxn.commit()此函数包含在SQL类中,能轻松将Pandas dataframe插入SQL数据库 。
 
其在需要上传大量文件时非常有用 。然而,Python能将数据插入到SQL的真正原因在于其灵活性 。
 
要横跨一打Excel工作簿才能在SQL中插入特定标签真的很糟心 。但有Python在,小菜一碟 。如今已经构建起了一个可以使用Python读取标签的函数,还能将标签插入到SQL中 。
 
Manual(函数)
 
defmanual(self, query,response=False):cursor = self.cnxn.cursor()# create execution cursorif response:returnread_sql(query,self.cnxn)# get sql queryoutput to dataframetry:cursor.execute(query)# executeexcept pyodbc.ProgrammingErroras error:print("Warning:n{}".format(error))# print error as a warningself.cnxn.commit()# commit query to SQL Serverreturn"Querycomplete."此函数实际上应用在union 和 drop 函数中 。仅能使处理SQL代码变得尽可能简单 。
 
response参数能将查询输出解压到DataFrame 。generic_jan 表中的colX ,可供摘录所有独特值,操作如下:
 
sets =list(sql.manual("SELECT colX AS 'category' FROM generic_jan GROUP BYcolX", response=True)['category'])Union(函数)
 
构建 了manual 函数,创建 union 函数就简单了:
 
defunion(self,table_list, name="union", join="UNION"):# initialise the queryquery ="SELECT *INTO ["+name+"] FROM (n"# build the SQL queryquery +=f'n{join}n'.join([f'SELECT [{x}].* FROM [{x}]'for x in table_list])query +=")x"# add end ofqueryself.manual(query, fast=True)# fast execute创建 union 函数只不过是在循环参考 table_list提出的表名,从而为给定的表名构建 UNION函数查询 。然后用self.manual(query)处理 。
Drop(函数)
 
上传大量表到SQL服务器是可行的 。虽然可行,但会使数据库迅速过载 。为解决这一问题,需要创建一个drop函数:
 
defdrop(self,tables):# check if single or listifisinstance(tables, str):# if singlestring, convert to single item in list for for-looptables = [tables]for table in tables:# check forpre-existing table and delete if presentquery = ("IFOBJECT_ID ('["+table+"]', 'U')IS NOT NULL ""DROP TABLE["+table+"]")self.manual(query)# execute 
view rawpysqlplus_drop_short.py hosted with ? by GitHub
点击
https://gist.github.com/jamescalam/b316c1714c30986fff58c22b00395cc0
得全图
同样,此函数也由于 manual 函数极为简单 。操作者可选择输入字符到tables ,删除单个表,或者向tables提供一列表名,删除多个表 。
当这些非常简单的函数结合在一起时,便可以利用Python的优势极大丰富SQL的功能 。
笔者本人几乎天天使用此法,其简单且十分有效 。
希望能够帮助其他用户找到将Python并入其SQL路径的方法,感谢阅读!




推荐阅读