I have used a 'class' named 'CMS'. Also,i have defined a method def ConnectDB(),Where i have loaded the driver and created a cursor object to execute a query.Whenever i try to access the cursor object,it's giving me an attribute error.
obj.cursor.execute(sql,v)
AttributeError: CMS instance has no attribute 'cursor'
How do I resolve it?Refer the code below to understand the problem statement clearly.Thanks in advance.
class CMS:
def ConnectDB(self):
server = '192.121.063.012'
database = 'fghr_db'
username = 'abcdef'
password = 'zzzzzzz'
connStr = 'DRIVER=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql- 17.2.so.0.1;SERVER='+server+';DATABASE='+database+';'+ 'UID='+username+'; PWD='+ password+';Port=1270'
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
def ReadCsv(self,filepath):
data = csv.reader(open(filepath))
print data
h=data.next()
result=[]
for x in data:
c=list(x)
result.append(c)
return result
obj=CMS()
obj.ConnectDB()
sql="INSERT INTO StudentCsv VALUES (?,?,?,?,?)"
z=obj.ReadCsv("Student.csv")
for v in z:
print v
obj.cursor.execute(sql,v)
obj.cnxn.commit()
ERROR getting like below:
obj.cursor.execute(sql,v) AttributeError: CMS instance has no
attribute 'cursor'
Related
Running into issue while registering user defined function in spark using python code, it throws error message "Could not serialize object: Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation"
Here is code snippet.
%python
def checkColumnNames(columnName,inputFilePath):
filePath = inputFilePath
data = spark.read.parquet(filePath)
columnNames = data.limit(1).columns
toreturn = 0
if columnName in columnNames:
toreturn = 1
else:
toreturn = 0
return (toreturn)
sqlContext.udf.register("checkColumnNames", checkColumnNames)
Can someone help me on this?
I am using Ubuntu as OS, pymysql, flask, sqlalchemy frameworks. Then I do GET request I have this error:
File "/srv/MSH/venv/local/lib/python2.7/site-packages/pymysql/converters.py", line 73, in _escape_unicode
return value.translate(_escape_table)
AttributeError: 'builtin_function_or_method' object has no attribute 'translate'
My routes.py code:
#app.route('/device/<dev_id>/<name>/<dev_type>/<state>', methods=['GET'])
def device(dev_id, state, dev_type, name):
# This function communicates with device
dev_state = 0
device = Devices.query.filter_by(dev_id=id).first()
# Check state
if state == "0":
state = False
if state == "1":
state = True
if device is None:
# if we don't know device write to database
dev = Devices(dev_id=dev_id, type=dev_type, prev_state=state, name=name)
db.session.add(dev)
db.session.commit()
return "hi"
else:
# Write data to database and return wanted state
device.prev_state = state
if device.state:
dev_state = 1
if not device.state:
dev_state = 0
db.session.commit()
return str(dev_state)
Wrong line here:
device = Devices.query.filter_by(dev_id=id).first()
You are query sql with something identical to internal python function. I think correct string is:
device = Devices.query.filter_by(dev_id=dev_id).first()
I am new to both python and SQLAlchemy. I am on python 3
I created a class testtbl to manipulate tables. One function is the update where I pass :
myfilter = {'origin_source_id':'MX01’}.
find this row in mysql table where origin_source_id = ‘MX01'
updatevalue = {'origin_source_id':'CAL01’}
replace the found origin_source_id by ‘CAL01;
The call
testtbl.update_row(myfilter,updatevalue)
The function
def update_row(self,locaterowfilter,updatevalue):
self.Session.query( self.TableClass ).filter_by( **locaterowfilter ).update( updatevalue )
I receive the following error
target_cls = query._mapper_zero().class_
AttributeError: 'NoneType' object has no attribute ‘class_’
I have no idea how to deal with it.
Is there a better way to do that?
The error is the result of passing a Table object as the primary entity of a query and trying to use Query.update():
In [26]: t = Table('t', metadata,
...: Column('a', Integer))
In [27]: session.query(t).update({'a': 1})
...
.../python3.6/site-packages/sqlalchemy/orm/persistence.py in _do_pre_synchronize(self)
1383 def _do_pre_synchronize(self):
1384 query = self.query
-> 1385 target_cls = query._mapper_zero().class_
1386
1387 try:
AttributeError: 'NoneType' object has no attribute 'class_'
which means that your self.TableClass is not a mapped class. If you wish to do updates on a Table, use the Core update() constructs:
stmt = self.TableClass.update().\
where(and_(*[self.TableClass.c[key] == value
for key, value in locaterowfilter.items()])).\
values(updatevalue)
self.Session.execute(stmt)
I'm trying to create a Collection Class in Python to access the various collections in my db. Here's what I've got:
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
client = MongoClient()
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
# self.data_base = getattr(self.client, db)
# self.collObject = getattr(self.data_base, self.collection_name)
def getCollection(self):
data_base = getattr(self.client, self.db)
collObject = getattr(data_base, self.collection_name)
return collObject
def getCollectionKeys(self, collection):
"""Get a set of keys from a collection"""
keys_list = []
collection_list = collection.find()
for document in collection_list:
for field in document.keys():
keys_list.append(field)
keys_set = set(keys_list)
return keys_set
if __name__ == '__main__':
print"Begin Main"
agents = Collection('hkpr_restore','agents')
print "agents is" , agents
agents_collection = agents.getCollection
print agents_collection
print agents.getCollectionKeys(agents_collection)
I get the following output:
Begin Main
agents is <__main__.Collection instance at 0x10ff33e60>
<bound method Collection.getCollection of <__main__.Collection instance at 0x10ff33e60>>
Traceback (most recent call last):
File "collection.py", line 52, in <module>
print agents.getCollectionKeys(agents_collection)
File "collection.py", line 35, in getCollectionKeys
collection_list = collection.find()
AttributeError: 'function' object has no attribute 'find'
The function getCollectionKeys works fine outside of a class. What am I doing wrong?
This line:
agents_collection = agents.getCollection
Should be:
agents_collection = agents.getCollection()
Also, you don't need to use getattr the way you are. Your getCollection method can be:
def getCollection(self):
return self.client[self.db][self.collection_name]
I am retrieving the last id from mssql and trying to incrementing it and storing the fie name with the id.. But I am getting "Attribute error : Nonetype object has no attribute 'id'"..The code and the error goes here :
import Tkinter,tkFileDialog
import shutil
import pyodbc
cnxn = pyodbc.connect("DRIVER={SQL Server};SERVER=PAVAN;DATABASE=video;Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute("SELECT TOP 1 id FROM files ORDER BY id DESC ")
while 1:
row = cursor.fetchone()
if not row:
break
print row.id
cnxn.close()
middle = Tkinter.Tk()
def withdraw():
dirname = tkFileDialog.askopenfilename(parent=middle,initialdir="H:/",title='Please
select a file')
a="H:python(test)\py_"+row.id+".mp4"
b=shutil.copyfile(dirname,a)
if b!="":
print "Successfully Copied"
else:
print "Could not be copied"
B = Tkinter.Button(middle, text ="UPLOAD", command = withdraw)
middle.geometry("450x300+100+100")
middle.configure(background="black")
B.pack()
middle.mainloop()
The error I'm getting is:
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Users\hp\Desktop\upload.py", line 20, in withdraw
a="H:python(test)\py_"+row.id+".mp4"
AttributeError: 'NoneType' object has no attribute 'id'
This occurs when the you try to get id Attribute from object which is of None type ,
Here is a case :
>> a = None
>> a.id
AttributeError: 'NoneType' object has no attribute 'id'
So it might be the case object row is of None type , and you are trying to print row.id
You may check for the type of row using :
type(**row**)
With Regards
Deepak