亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實現(xiàn)SqlServer查詢結果并寫入多個Sheet頁的方法詳解

 更新時間:2022年12月06日 15:02:17   作者:Carl_奕然  
這篇文章主要為大家整理了兩個Python實現(xiàn)SqlServer查詢結果并寫入多個Sheet頁的方法,文中的示例代碼講解詳細,感興趣的可以了解一下

1、引言

小絲:魚哥,我想請教一個問題。

小魚:國慶假期你經(jīng)歷了什么,讓你變得如此的 “善良”?

小絲:別這么說,我一直很善良,至少,很正直…

小魚:打住,直接點, 你有什么需要幫助的?

小絲:我就是想把查詢的結果也入到excel表中

小魚:然后呢?

小絲:sqlserver數(shù)據(jù)庫。

小魚:…好吧,還有其他要求嗎?

小絲:沒有了。

小魚:OK,我就花費幾分鐘,給你整一個。

2、代碼實戰(zhàn)

2.1 openpyxl寫入excel

2.1.1 安裝

凡是涉及第三方庫,必須需要安裝,

老規(guī)矩,直接pip安裝

pip install openpyxl
pip install pymssql

其它安裝方式,直接看這兩篇:

《Python3,選擇Python自動安裝第三方庫,從此跟pip說拜拜?。 ?/a>

《Python3:我低調(diào)的只用一行代碼,就導入Python所有庫!》

2.1.2 代碼

代碼示例

# -*- coding:utf-8 -*-
# @Time   : 2022-10-10
# @Author : Carl_DJ


'''
實現(xiàn)功能:
    1、python直接鏈接sqlserver數(shù)據(jù)庫,讀取數(shù)據(jù)庫內(nèi)容
    2、執(zhí)行 查詢結果,并寫入到excel表中
應用模塊:
	pymssql,os,openpyxl

'''
import os
import pymysql #mysql數(shù)據(jù)庫鏈接
import pymssql #sqlserver數(shù)據(jù)庫鏈接
import openpyxl



#輸出文件夾
outfile_path = './data'

#如果沒有outfile_path 這個文件夾,就自動創(chuàng)建
if not os.path.exists(outfile_path):
    os.mkdir(outfile_path)

#輸出文件名稱
filename = r'SQLtest.xlsx'
file_path= os.path.join(outfile_path,old_filename)


#創(chuàng)建數(shù)據(jù)庫鏈接
#鏈接SqlServer
conn = pymssql.connect(host = "localhost",
					   port = 3306,
					   user = "",
					   psd = "",
					   database = "")

if conn:
    print("數(shù)據(jù)庫鏈接成功")

time.sleep(3)

#sql查詢語句
sql = "select UUID,KEYID,TYPE,NAME,PRICE from KEY_INFO WHERE NAME LIKE '%測試商品名稱'"


#創(chuàng)建游標
cur = conn.cursor()
#執(zhí)行sql語句
cur.execute(sql)

#返回查詢結果
result = cur.fetchall()

#創(chuàng)建一個工作簿對象
wb = openpyxl.Workbook()
#定義sheet名
Key_Info_sheet = wb.create_sheet('KEY_INFO ',0)

#獲取默認sheet頁
# Key_Info_sheet = book.active

#獲取表頭信息
h1 = [filed[0] for filed in cur.description]
Key_Info_sheet.append(h1)
for i in result:
    Key_Info_sheet.append(i)
wb.save(file_path)


# 關閉數(shù)據(jù)庫鏈接
cur.close()
conn.close()

執(zhí)行結果

嗯,這就非常完美的寫入excel了。

2.2 pandas寫入excel

小絲:魚哥,我這一次要執(zhí)行多個SQL語句,

小魚:… 你不是說沒有了嗎

小絲:突然想起來的。

小魚:好吧,還有其他的要求嗎?

小絲:然后把每個SQL查詢結果寫入不同的sheet頁

小魚:xxxxxx??!還有嗎????!?。?/p>

小絲:沒有了。

小魚:有也沒有。

關于小絲提的要求, 我換一個寫法,畢竟,多學幾個知(姿 )識(勢 ),百利而無一害。

2.2.1 安裝

這次有pandas來寫。

所以,第一步,安裝

pip install pandas

其它安裝方式,直接看這兩篇:

《Python3,選擇Python自動安裝第三方庫,從此跟pip說拜拜!!》

《Python3:我低調(diào)的只用一行代碼,就導入Python所有庫!》

2.2.2 代碼

sql文檔

代碼示例

# -*- coding:utf-8 -*-
# @Time   : 2022-10-10
# @Author : Carl_DJ

'''
實現(xiàn)功能:
    1、python直接鏈接SqlServer數(shù)據(jù)庫,實現(xiàn)SQL查詢
    2、同時執(zhí)行多條sql語句,查詢結果分別寫入不同的sheet頁中;
應用模塊:
    pandas,pymssql,os,time

'''
import pandas as pd
from pandas.io import sql
import pymssql
import time,os

#設置時間戳
now = time.strftime("%Y_%m_%d-%H%M%S",time.localtime())
print(f'執(zhí)行時間:{now}')

#創(chuàng)建數(shù)據(jù)庫鏈接
#鏈接SqlServer
conn = pymssql.connect(host = "localhost",
						port = 3306,
						user = "",
						psd = "",
						database = "")

if conn:
    print("數(shù)據(jù)庫鏈接成功")

time.sleep(3)

#輸出文件夾
file_path = './data'

#如果沒有outfile_path 這個文件夾,就自動創(chuàng)建
if not os.path.exists(file_path):
    os.mkdir(file_path)
    
#輸出文件格式
Outfile_name = ( 'SqlsTest' + now + '.xlsx')
#讀取sql文件名稱
sqls_name = r'SqlsFile.txt'
#sql執(zhí)行腳本文件(參數(shù)化路徑)
MCsql_file = os.path.join(file_path,MCsql_name)
#輸出文件夾路徑
Outfile_path = os.path.join(file_path,Outfile_name)

#把查詢結果寫入不同的sheet頁,對sheet頁進行命名
sheet_names = ['KEY_INFO','PRO_INFO']

#定義讀取sql方法,返回sql語句
def sqls(MCsql_file):
    global sqlstrs
    with open(MCsql_file,'r',encoding='utf-8') as f:
        #每個sql之間,以“;”作為分隔符
        sqlstrs = f.read().split(';')

#定義數(shù)據(jù)查詢方法
def quert_method(sql_str):
    #設置全局變量
    global df
    df = pd.read_sql(sql_str,con=conn)

#執(zhí)行程序
if __name__ == '__main__':
    sqls(MCsql_file)
    #寫入excel文件
    with pd.ExcelWriter(Outfile_path) as writer:
        for i in range(0,len(sqlstrs)):
            quert_method(sqlstrs[i])
            df.to_excel(writer,sheet_name=sheet_names[i],index=False,header=True)

print("數(shù)據(jù)寫入完成!")

# 關閉數(shù)據(jù)庫鏈接
conn.close()
print("數(shù)據(jù)庫鏈接關閉!")

執(zhí)行結果

3、總結

看到這里,今天的分享差不多就完成了。

今天主要通過鏈接SqlServer數(shù)據(jù)庫,把查詢數(shù)據(jù)結果寫入到excel表中。

同時,應用openpyxl 和pandas兩個模塊,分別對excel的操作。

到此這篇關于Python實現(xiàn)SqlServer查詢結果并寫入多個Sheet頁的方法詳解的文章就介紹到這了,更多相關Python寫入多個Sheet頁內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論