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


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

文章插图
来源:Pexels
 
笔者在工作中经常要使用SQL,其不乏存在恼人的细微差异和种种限制,但说到底,它是数据行业的基石 。因此,对于每一位数据领域的工作者,SQL都是不可或缺的 。精通SQL意义非凡 。
 
SQL是很不错,但怎么能仅满足于“不错”呢?为什么不进一步操作SQL呢?
 
陈述性语句会诱发SQL限制的发生,就是说,向SQL寻求数据,SQL会在特定数据库找寻并反馈 。对于许多数据提取或简单的数据操作任务来说,这已经足够了 。
 
但如果有更多需求怎么办?
 
本文将为你展示如何操作 。
 
从基础开始import pyodbcfrom datetime import datetimeclassSql:def__init__(self,database, server="XXVIR00012,55000"):# here we aretelling Python what to connect to (our SQL Server)self.cnxn = pyodbc.connect("Driver={SQLServer Native Client 11.0};""Server="+server+";""Database="+database+";""Trusted_Connection=yes;")# initialisequery attributeself.query ="--{}nn-- Made in Python".format(datetime.now().strftime("%d/%m/%Y"))这个代码就是操作MS SQL服务器的基础 。只要编写好这个代码,通过Python 连接到SQL 仅需:
 
sql = Sql('database123')很简单对么?同时发生了几件事,下面将对此代码进行剖析 。class Sql:
 
首先要注意,这个代码包含在一个类中 。笔者发现这是合乎逻辑的,因为在此格式中,已经对此特定数据库进行了增添或移除进程 。若见其工作过程,思路便能更加清晰 。
 
初始化类:
 
def __init__(self, database,server="XXVIR00012,55000"):因为笔者和同事几乎总是连接到相同的服务器,所以笔者将这个通用浏览器的名称设为默认参数server 。
 
在“Connect to Server”对话框或者MS SQL Server Management Studio的视窗顶端可以找到服务器的名称:
 
如何利用Python实现SQL自动化?

文章插图
 
 
下一步,连接SQL:
 
self.cnxn =pyodbc.connect("Driver={SQL Server Native Client 11.0};""Server="+self.server+";""Database="+self.database+";""Trusted_Connection=yes;")pyodbc 模块,使得这一步骤异常简单 。只需将连接字符串过渡到 pyodbc.connect(...) 函数即可,点击以了解详情here 。
 
最后,笔者通常会在 Sql 类中编写一个查询字符串,sql类会随每个传递给类的查询而更新:
self.query = "-- {}nn--Made in Python".format(datetime.now().strftime("%d/%m/%Y"))这样便于记录代码,同时也使输出更为可读,让他人读起来更舒服 。
 
请注意在下列的代码片段中,笔者将不再更新代码中的self.query 部分 。
 
组块 
一些重要函数非常有用,笔者几乎每天都会使用 。这些函数都侧重于将数据从数据库中传入或传出 。
 
以下图文件目录为始:
 
如何利用Python实现SQL自动化?

文章插图
 
 
对于当前此项目,需要:
 
· 将文件导入SQL
· 将其合并到单一表格内
· 根据列中类别灵活创建多个表格
 
SQL类不断被充实后,后续会容易很多:
【如何利用Python实现SQL自动化?】 
import syssys.path.insert(0, r'C:\Usermediumpysqlpluslib')import osfrom data importSqlsql =Sql('database123')# initialise the Sql objectdirectory =r'C:\Usermediumdata\'# this is where our generic data isstoredfile_list = os.listdir(directory)# get a list of all filesfor file infile_list:# loop to importfiles to sqldf = pd.read_csv(directory+file)# read file to dataframesql.push_dataframe(df, file[:-4])# now weconvert our file_list names into the table names we have imported to SQLtable_names = [x[:-4] for x in file_list]sql.union(table_names, 'generic_jan')# union our files into one new tablecalled 'generic_jan'sql.drop(table_names)# drop our original tables as we nowhave full table# get list ofcategories in colX, eg ['hr', 'finance', 'tech', 'c_suite']sets =list(sql.manual("SELECTcolX AS 'category' FROM generic_jan GROUP BY colX", response=True)['category'])for category in sets:sql.manual("SELECT *INTO generic_jan_"+category+" FROMgeneric_jan WHERE colX = '"+category+"'")


推荐阅读