将查询结果写入 SSMS

Wtriting query results into SSMS

我试图将 python 中的查询 (API) 的结果写入 SQL 服务器数据库,但我迷失在什么是显然是一个菜鸟错误。 “字符串索引超出范围”。

是的,我不是开发人员,我的代码是数小时阅读、社区帮助和 google 研究的结果。

你们能帮助我了解我的错误在哪里以及如何解决吗?

from re import X
from typing import ItemsView
import requests
import json
import hashlib
import base64
import time
import hmac
import pandas as pd
import datetime
import pyodbc

#Account Info
AccessId = ''
AccessKey = ''
Company = ''

#Request Info
httpVerb ='GET'
resourcePath = '/alert/alerts'


queryParams ='?size=1000&sort=-startEpoch&filter=cleared:*'
#queryParams ='?size=1000&filter=cleared:False'
#queryParams ='?size=1000&filter=cleared:%252A'

#queryParams ='?v=2&size=1000&offset=9000&filter=cleared:"*"'

data = ''

#Construct URL 
url = 'https://'+ Company +'.logicmonitor.com/santaba/rest' + resourcePath + queryParams

print(url)

#Get current time in milliseconds
epoch = str(int(time.time() * 1000))

#Concatenate Request details
requestVars = httpVerb + epoch + data + resourcePath

#Construct signature
hmac1 = hmac.new(AccessKey.encode(),msg=requestVars.encode(),digestmod=hashlib.sha256).hexdigest()
signature = base64.b64encode(hmac1.encode())

#Construct headers
auth = 'LMv1 ' + AccessId + ':' + signature.decode() + ':' + epoch
headers = {'Content-Type':'application/json','Authorization':auth}

#Make request
response = requests.get(url, data=data, headers=headers)

data = response.json()

alerts_df = pd.DataFrame(data['data']['items'])
#alerts_df = alerts_df.groupby(['id'], as_index=False).first()
alerts_df = alerts_df[['id','internalId','rule','monitorObjectName','startEpoch','endEpoch','cleared','resourceTemplateName']]
alerts_df['startEpoch'] = pd.to_datetime(alerts_df['startEpoch'],unit='s')
alerts_df['endEpoch'] = alerts_df['endEpoch'].apply(lambda x: pd.to_datetime(x,unit='s') if x !=0 else x)
alerts_df = alerts_df.loc[alerts_df["rule"] == "Critical"]


print(alerts_df)
#print(alerts_df.shape)

#alerts_df.to_csv("alerts_no_groupedby_03.csv")
#alerts_df.to_sql("critical_alerts_00", sqlite3, if_exists='replace', index = False)

server = '999999\SQLEXPRESS'
database = 'LM_Critical_Alerts'

# define connection string
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; \
                        SERVER=' + server + '; \
                        DATABASE=' + database +'; \
                        Trusted_Connection=yes;')

# create the connection cursor
cursor = cnxn.cursor()

# define insert query
insert_query = '''INSERT INTO critical_alerts (row, id, internalId, alertType, monitorObjectName, startEpoch, endEpoch, cleared, resourceTemplateName)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);'''

# loop through each row in the matrix
for row in alerts_df:

    # define the values to insert
    values = (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8])

    # insert the data into the database
    cursor.execute(insert_query, values)

# commit the inserts
cnxn.commit()

# grab all the rows in the database table
cursor.execute('SELECT * FROM critical_alerts')

# loop through the results
for row in cursor:
    print(row)

错误信息和数据结构:

                    id   internalId      rule          monitorObjectName          startEpoch             endEpoch  cleared        resourceTemplateName
13   DS25095821   LMD1815378  Critical                 MYSERVER 2022-04-20 01:24:55                    0    False                         CPU
120  DS25095744   LMD4168355  Critical               MYSERVER   2022-04-20 00:34:40  2022-04-20 00:38:40     True        Memory and Processes
149  DS25095716   LMD1815378  Critical                 MYSERVER 2022-04-20 00:16:08  2022-04-20 01:05:54     True                         CPU
178  DS25095682  LMD10870447  Critical                   MYSERVER   2022-04-20 00:03:13  2022-04-20 00:08:40     True        SQL Server Databases
179  DS25095683  LMD10863782  Critical                   MYSERVER   2022-04-20 00:03:13  2022-04-20 00:08:40     True        SQL Server Databases
180  DS25095684  LMD10866820  Critical                   MYSERVER   2022-04-20 00:03:13  2022-04-20 00:08:40     True        SQL Server Databases
181  DS25095685  LMD10868897  Critical                   MYSERVER   2022-04-20 00:03:13  2022-04-20 00:08:40     True        SQL Server Databases
207  DS25095665  LMD12336087  Critical                   MYSERVER   2022-04-19 23:56:08  2022-04-20 00:02:10     True        SQL Server Databases
208  DS25095666  LMD12335870  Critical                 MYSERVER 2022-04-19 23:56:08  2022-04-20 00:02:10     True        SQL Server Databases
209  DS25095667  LMD12336893  Critical                 MYSERVER 2022-04-19 23:56:08  2022-04-20 00:02:10     True        SQL Server Databases
210  DS25095668  LMD12335901  Critical                 MYSERVER 2022-04-19 23:56:08  2022-04-20 00:02:10     True        SQL Server Databases
270  DS25095620  LMD10866820  Critical                 MYSERVER 2022-04-19 23:33:14  2022-04-19 23:45:14     True        SQL Server Databases
272  DS25095619  LMD12474939  Critical                 MYSERVER 2022-04-19 23:32:14  2022-04-19 23:35:14     True  Elekta MOSAIQ App Services
274  DS25095617   LMD1815378  Critical                 MYSERVER 2022-04-19 23:31:48  2022-04-19 23:52:36     True                         CPU
400  DS25095526   LMD1815378  Critical                 MYSERVER 2022-04-19 22:52:45  2022-04-19 23:02:12     True                         CPU
436  DS25095501  LMD12006224  Critical               MYSERVER   2022-04-19 22:37:37  2022-04-19 22:39:42     True                         CPU
455  DS25095490   LMD1815378  Critical                 MYSERVER 2022-04-19 22:30:18  2022-04-19 22:40:45     True                         CPU
473  DS25095472  LMD10863472  Critical                   MYSERVER   2022-04-19 22:20:46  2022-04-19 22:44:37     True        SQL Server Databases
510  DS25095449  LMD12006813  Critical               MYSERVER   2022-04-19 22:06:59  2022-04-19 22:42:32     True                         CPU
555  DS25095424  LMD12006224  Critical               MYSERVER   2022-04-19 21:47:22  2022-04-19 22:26:12     True                         CPU
628  DS25095366  LMD12006813  Critical               MYSERVER   2022-04-19 21:14:52  2022-04-19 21:49:43     True                         CPU
697  DS25095328   LMD3090757  Critical               MYSERVER   2022-04-19 20:51:41  2022-04-19 21:11:40     True        Memory and Processes
737  DS25095293  LMD12006813  Critical               MYSERVER   2022-04-19 20:38:47  2022-04-19 20:43:34     True                         CPU
851  DS25095220  LMD12006224  Critical               MYSERVER   2022-04-19 19:56:31  2022-04-19 21:25:58     True                         CPU
894  DS25095183  LMD12006224  Critical               MYSERVER   2022-04-19 19:34:23  2022-04-19 19:44:31     True                         CPU
916  DS25095165  LMD12006813  Critical               MYSERVER   2022-04-19 19:25:53  2022-04-19 20:26:38     True                         CPU
Traceback (most recent call last):
  File "c:\Users\Nelson.Silva\OneDrive - Computer & Network Solutions Limited\PBI\LM_Python_Queries\query_alerts.py", line 91, in <module>
    values = (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8])
IndexError: string index out of range

当你这样做时:

for row in alerts_df:
    values = (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8])

您没有遍历行。

试试这个:

for index, row in alerts_df.iterrows():
    values = (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8])