温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么实现SQL自动化

发布时间:2021-07-05 17:39:15 来源:亿速云 阅读:202 作者:Leah 栏目:编程语言

这篇文章给大家介绍Python中怎么实现SQL自动化,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

从基础开始

import pyodbc from datetime import datetime classSql:     def__init__(self,  database, server="XXVIR00012,55000"):         # here we are  telling python what 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的视窗顶端可以找到服务器的名称:

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 = "-- {}\n\n--Made in Python".format(datetime.now()                                              .strftime("%d/%m/%Y"))

这样便于记录代码,同时也使输出更为可读,让他人读起来更舒服。

请注意在下列的代码片段中,笔者将不再更新代码中的self.query 部分。

组块

一些重要函数非常有用,笔者几乎每天都会使用。这些函数都侧重于将数据从数据库中传入或传出。

以下图文件目录为始:

Python中怎么实现SQL自动化

对于当前此项目,需要:

  • 将文件导入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


关于Python中怎么实现SQL自动化就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI