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

上一篇 / 下一篇  2020-03-18 14:54:20

笔者在工作中经常要使用SQL,其不乏存在恼人的细微差异和种种限制,但说到底,它是数据行业的基石。因此,对于每一位数据领域的工作者,SQL都是不可或缺的。精通SQL意义非凡。
  SQL是很不错,但怎么能仅满足于“不错”呢?为什么不进一步操作SQL呢?
  陈述性语句会诱发SQL限制的发生,就是说,向SQL寻求数据,SQL会在特定数据库找寻并反馈。对于许多数据提取或简单的数据操作任务来说,这已经足够了。
  但如果有更多需求怎么办?
  本文将为你展示如何操作。
  从基础开始
   import pyodbc
  from datetime import datetime
  classSql:
  def__init__(self,  database,server="XXVIR00012,55000"):
  # here we are  tellingpythonwhat to connect to (our SQL Server)
  self.cnxn = pyodbc.connect("Driver={SQL  Server Native Client 11.0};"
  "Server="+server+";"
  "Database="+database+";"
  "Trusted_Connection=yes;")
  # initialise  query attribute
  self.query ="--  {}\n\n-- 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的视窗顶端可以找到服务器的名称:
  下一步,连接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 = "-- {}\n\n--Made in Python".format(datetime.now()
  .strftime("%d/%m/%Y"))
  这样便于记录代码,同时也使输出更为可读,让他人读起来更舒服。
  请注意在下列的代码片段中,笔者将不再更新代码中的self.query 部分。
  组块
  一些重要函数非常有用,笔者几乎每天都会使用。这些函数都侧重于将数据从数据库中传入或传出。
  以下图文件目录为始:
  对于当前此项目,需要:
  将文件导入SQL
  将其合并到单一表格内
  根据列中类别灵活创建多个表格
  SQL类不断被充实后,后续会容易很多:
   import sys
  sys.path.insert(0, r'C:\\User\medium\pysqlplus\lib')
  import os
  from data importSql
  sql =Sql('database123')  # initialise the Sql object
  directory =r'C:\\User\medium\data\\'  # this is where our generic data is  stored
  file_list = os.listdir(directory)  # get a list of all files
  for file in  file_list:  # loop to import  files to sql
  df = pd.read_csv(directory+file)  # read file to dataframe
  sql.push_dataframe(df, file[:-4])
  # now we  convert our file_list names into the table names we have imported to SQL
  table_names = [x[:-4] for x in file_list]
  sql.union(table_names, 'generic_jan')  # union our files into one new table  called 'generic_jan'
  sql.drop(table_names)  # drop our original tables as we now  have full table
  # get list of  categories in colX, eg ['hr', 'finance', 'tech', 'c_suite']
  sets =list(sql.manual("SELECT  colX AS 'category' FROM generic_jan GROUP BY colX", response=True)['category'])
  for category in sets:
  sql.manual("SELECT *  INTO generic_jan_"+category+" FROM  generic_jan WHERE colX = '"+category+"'")
  从头开始。
  入栈数据结构
   defpush_dataframe(self, data,  table="raw_data", batchsize=500):
  # create execution cursor
  cursor = self.cnxn.cursor()
  # activate fast execute
  cursor.fast_executemany =True
  # create create table statement
  query ="CREATE  TABLE ["+ table +"] (\n"
  # iterate through each column to be  included in create table statement
  for i inrange(len(list(data))):
  query +="\t[{}]  varchar(255)".format(list(data)[i])  # add column (everything is varchar  for now)
  # append correct  connection/end statement code
  if i !=len(list(data))-1:
  query +=",\n"
  else:
  query +="\n);"
  cursor.execute(query)  # execute the create table statement
  self.cnxn.commit()  # commit changes
  # append query to our SQL code logger
  self.query += ("\n\n--  create table\n"+ query)
  # insert the data in batches
  query = ("INSERT  INTO [{}] ({})\n".format(table,
  '['+'], ['  # get columns
  .join(list(data)) +']') +
  "VALUES\n(?{})".format(",  ?"*(len(list(data))-1)))
  # insert data into target table in  batches 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 batch  insert
  cursor.executemany(query, batch)
  # commit insert  to SQL Server
  self.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 cursor
  if response:
  returnread_sql(query,  self.cnxn)  # get sql query  output to dataframe
  try:
  cursor.execute(query)  # execute
  except pyodbc.ProgrammingErroras error:
  print("Warning:\n{}".format(error))  # print error as a warning
  self.cnxn.commit()  # commit query to SQL Server
  return"Query  complete."
  此函数实际上应用在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 query
  query ="SELECT *  INTO ["+name+"] FROM (\n"
  # build the SQL query
  query +=f'\n{join}\n'.join(
  [f'SELECT [{x}].* FROM [{x}]'for x in table_list]
  )
  query +=")  x"  # add end of  query
  self.manual(query, fast=True)  # fast execute
  创建 union 函数只不过是在循环参考 table_list提出的表名,从而为给定的表名构建 UNION函数查询。然后用self.manual(query)处理。
  Drop(函数)
  上传大量表到SQL服务器是可行的。虽然可行,但会使数据库迅速过载。 为解决这一问题,需要创建一个drop函数:
   defdrop(self,  tables):
  # check if single or list
  ifisinstance(tables, str):
  # if single  string, convert to single item in list for for-loop
  tables = [tables]
  for table in tables:
  # check for  pre-existing table and delete if present
  query = ("IF  OBJECT_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路径的方法,感谢阅读!

TAG:

 

评分:0

我来说两句

Open Toolbar