Home > Software design >  AttributeError: 'pyodbc.Connection' object has no attribute 'executemany'
AttributeError: 'pyodbc.Connection' object has no attribute 'executemany'

Time:10-26

these are 2 classes dbclient and mykiosk client, im trying to run those 4 lines of code below but Im getting the AttributeError. I just want to get api data into sql table through python keeping this format in mind. Can someone please help me out?

db =DatabaseClient()
mk = MyKiosk()

freq_data = mk.get_frequency_data()
db.write_frequency_data(freq_data)

class DatabaseClient:
    def __init__(self):
        self.connect()
    
    def connect(self):
        server = "sql-test-server-vdzbi.database.windows.net"
        database = "sql-test-database-vdzbi"
        username = "vdzbi-admin"
        password = "VD9ffqjHaugvTf2"
        self.cursor = pyodbc.connect("DRIVER={SQL Server};SERVER=" server ";DATABASE=" database ";UID=" username ";PWD=" password)
        
    
    def write_frequency_data(self, data):
       # self.cursor.fast_executemany = True
        
        stage_query = "INSERT INTO staging.Frequency (FreqId, Title) VALUES (?,?)"
        merge_query = """INSERT INTO mykiosk.Frequency(FreqId, Title) 
            SELECT FreqId, Title
            FROM staging.Frequency stage 
            WHERE stage.FreqId not in (Select FreqId from mykiosk.Frequency)"""
        truncate_query = "TRUNCATE TABLE staging.Frequency"
            
        try:
            self.cursor.executemany(stage_query,data)
            self.cursor.executemany(merge_query,data)

######### api.py file ###########

import requests
import json
import simplejson


class MyKiosk:
    object_endpoint = "/api/Objektgruppe/GetObjektgruppen"
    price_endpoint = "/api/Objekt/getObjekteByHauptgruppeId"
    frequency_endpoint = "/api/erscheinungsweise/GetErscheinungsweisen"

    def __init__(self):
        self.host = "https://www.mykiosk.com"

    def get_frequency_data(self):
        
        # endpoint = "/api/Objektgruppe/GetObjektsgruppen"
        r = requests.get(f"{self.host}/{self.frequency_endpoint}")
        assert r.status_code == 200
        freq = r.json()
        data =[]
        for i in freq:
            val = (i["ErscheinungsweiseId"], i["Bezeichnung"])
            data.append(val)
        return data
            
    

CodePudding user response:

Raised error was wrong.

You assigned pyodbc.Connection instead of pyodbc.Cursor to self.cursor.

You should assign connect().cursor().

Change line:

self.cursor = pyodbc.connect("DRIVER={SQL Server};SERVER=" server ";DATABASE=" database ";UID=" username ";PWD=" password)

To:

connection = pyodbc.connect("DRIVER={SQL Server};SERVER=" server ";DATABASE=" database ";UID=" username ";PWD=" password)
self.cursor = connection.cursor()
        
  • Related