import pyodbc
class Database(object):
def connect(self):
connection = pyodbc.connect("""DRIVER={SQL Server};
SERVER=XX\SQLEXPRESS;
DATABASE=ACCOUNT_DBF;
UID=sa;PWD=XXX""")
cursor = connection.cursor()
def check_account(self, usr):
cursor.execute("SELECT * FROM ACCOUNT_TBL WHERE account = ?", usr)
row = cursor.fetchone()
print(row[0])
database = Database()
database.check_account("developer")
So, as you can see I am trying to call the "check_account" function with the parameter of "developer". But whenever I execute/build it, it gives me an error of
"NameError: name cursor not defined"
I am curious and new to python on how to actually do it. I've been searching around the web but I cannot find a specific answer for my problem.
*I am using the latest python btw(3.6.1).
The NameError exception is triggered because in the check_account method you can not see local variables defined in connect method.
You need to set instance attributes "inside" self, since you can access self from all methods (it is the instance itself).
def connect(self):
self.connection = pyodbc.connect("""DRIVER={SQL Server};
SERVER=XX\SQLEXPRESS;
DATABASE=ACCOUNT_DBF;
UID=sa;PWD=XXX""")
self.cursor = connection.cursor()
def check_account(self, usr):
self.cursor.execute("SELECT * FROM ACCOUNT_TBL WHERE account = ?", usr)
row = self.cursor.fetchone()
print(row[0])
Try:
class Database(object):
def connect(self):
connection = pyodbc.connect("""DRIVER={SQL Server};
SERVER=XX\SQLEXPRESS;
DATABASE=ACCOUNT_DBF;
UID=sa;PWD=XXX""")
self.cursor = connection.cursor()
In your code, cursoris variable which below to method, only self.cursor can store cursor to class, and then other methods can use.
Related
actually I was using mysql-python connector using code below
cnx = mysql.connector.connect(user='root', password='passw',
host='localhost',database='dhruv_12')
cnx.close()
but when I executed the above code, it shows a error as below
File ~\Desktop\I.P class 12\practical file class 12\untitled0.py:3 in <module>
cnx = mysql.connector.connect(user='root', password='tiger',
AttributeError: module 'mysql.connector' has no attribute 'connect'
I reinstalled python , reinstalled python-mysql-connector using pip and even tried changing file name but nothing happen .
I executed same code in python IDLE , it worked properly . But it doesn't worked in spyder . My spyder version is up to date . Please help me with this , I really need help because of my project
at school. Please help me as soon as possible , Its my request....
Try importing connect as shown below.
Use a with statement to automatically close the connection.
"""Demonstrates creating a database connection and inserting and reading data."""
from mysql.connector import connect, Error
class SqlTest:
"""Demo class to connect, insert, and query data from a database."""
def __init__(self, db_host, db_port, db_name, db_user_name, db_password):
"""Initialize object properties."""
# Fields
self._db_port = db_port
self._db_name = db_name
self._db_host = db_host
self._db_user_name = db_user_name
self._db_password = db_password
self.db_connection = None
# Constants
self.SELECT_ALL = 'SELECT id, item, count FROM items'
self.INSERT = 'INSERT INTO items (item, count) VALUES(%s, %s)'
def insert_item(self, item, count):
try:
with connect(
host=self._db_host,
user=self._db_user_name,
password=self._db_password,
database=self._db_name,
port=self._db_port
) as connection:
cursor = connection.cursor()
cursor.execute(self.INSERT, (item, count))
connection.commit() # Very important!
cursor.close()
except Error as e:
print(e)
def query_all(self):
results = None
try:
with connect(
host=self._db_host,
user=self._db_user_name,
password=self._db_password,
database=self._db_name,
port=self._db_port
) as connection:
cursor = connection.cursor()
cursor.execute(self.SELECT_ALL)
results = cursor.fetchall()
except Error as e:
print(e)
return results
What I'm trying to achieve
Create a database connection pool in Django. The connection pool is connected to a PostgreSQL database by using SQLAlchemy's connection pooling with django-postgrespool2.
Thrown exception
'psycopg2.extensions.connection' object is not callable is thrown when running the following line of code poolConnection = dbPool.connect(). Printing the dbPool object and type displays <sqlalchemy.pool.impl.QueuePool object at 0x00000171832A72B0> <class 'sqlalchemy.pool.impl.QueuePool'>
Code
Database helper class which creates the connection to the PostgreSQL database and creates the connection pool:
import psycopg2
from sqlalchemy import pool
import traceback
dbPool = None
class DbPoolHelper:
def ensurePoolCreated(self):
global dbPool
if dbPool != None:
return
self.createPool()
def dbConnect(self):
dbConnection = psycopg2.connect(user="...", password="...", dbname="...", host="...",port="...")
return dbConnection
def createPool(self):
dbConnection = self.dbConnect()
global dbPool
dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5)
def execute(self, sql, sqlParams):
try:
global dbPool
self.ensurePoolCreated()
poolConnection = dbPool.connect()
cursor = poolConnection.cursor()
cursor.execute(sql, sqlParams)
poolConnection.commit()
result = cursor.fetchall()
cursor.close()
poolConnection.close()
return result
except Exception as e:
print(e)
return e
The code using the DbPoolHelper to fetch some data by using the execute method and giving some sql and sql params as arguments:
def poolTest():
sql = "SELECT * FROM sysproductcontainers;"
sqlParams = ()
db = DbPoolHelper()
result = db.execute(sql, sqlParams)
Question
Why does the code throw 'psycopg2.extensions.connection' object is not callable?
Keep in mind that I am pretty new to Python and Django. So I might be missing something obvious to some Python and/or Django developers.
Thanks!
According to the QueuePool docs the first argument should be 'a callable function that returns a DB-API connection object'.
You've passed the result of the called function to the QueuePool object as the first argument instead of the function itself. Remove the parenthesis to solve the issue:
def createPool(self):
dbConnection = self.dbConnect
global dbPool
dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5)
I am trying to access cursor outside the function dbconnect(). But I am getting this error "AttributeError: 'function' object has no attribute 'cursor'"
It would be really great if somebody could fix it. I am trying to make a program for school project. Code is given below.
import mysql.connector as mysql
def dbconnect():
db = mysql.connect(host='',
database='',
user='',
password='')
cursor = db.cursor()
return cursor
query = "select name,atomic_weight from elements where atomic_number = 8"
dbconnect.cursor.execute(query)
result = dbconnect.cursor.fetchall()
print(result)
cursor = dbconnect()
cursor.execute(query)
result = cursor.fetchall()
I currently have many scripts that connect to the same MSSQL database. I make the connection in each of the scripts, but for ease of use I want to put the connection in a module and call that module from my script. The code in my module connect_to_db.pyc looks like this:
import pyodbc
def sql_connect():
server="some_server.net"
port="1433"
user = "my_username#my_domain"
server="my_server"
database="my_database"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433',
user=user,
password=password,
database=database)
c=conn.cursor()
Then, in my script I try to call this module and run a query:
from connect_to_db import sql_connect
sql_connect()
c.execute("SELECT * FROM table")
I get the error that the name c is not defined. I tried to define it as a global too, but it don't help. It must have something to do with my lack of understanding modules, but I can't figure out what.
You can return cursor in your sql_connect function
import pyodbc
def sql_connect():
server="some_server.net"
port="1433"
user = "my_username#my_domain"
server="my_server"
database="my_database"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433',
user=user,
password=password,
database=database)
return conn.cursor()
And then you can use it as
from connect_to_db import sql_connect
c = sql_connect()
c.execute("SELECT * FROM table")
You are indeed missing a bit there:
in your function sql_connect, you assign to a local variable named c.
That variable is not existant outside your function.
If you want a connection variable to exist on module level, maybe try the following attempt:
In your "connect_to_db.py":
import pyodbc
def sql_connect():
server="some_server.net"
port="1433"
user = "my_username#my_domain"
server="my_server"
database="my_database"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433',
user=user,
password=password,
database=database)
return conn.cursor()
cursor = sql_connect()
This creates a varibale "cursor" on the level of the module.
In another module, simply perform
from connect_to_db import cursor
to import the module's "cursor" member.
This should do the trick.
Hint: Please be advised that this approach may not be very elegant, in terms of software-engineering.
Edit:
Maybe, you may want to dive deeper into object-oriented programming?
class MSSQLConnector(object):
def __init__(self, server, port, database, user, password):
self.server = server
self.port = port
self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER='{0},
{1}.format((self.server, self.port)), user, password, database)
def open_cursor(self):
return self.conn.cursor()
Which would be used in this fashion:
connector = MSSQLConnector("my_server", "1433", "my_database", "username", "secret-password")
cursor = connector.open_cursor()
I have a simple web.py-based app that uses MySQLdb. I have a class that handles database operations like so:
class db():
def __init__(self):
db = MySQLdb.connect(host='mysql.server', user='user', passwd='pass', db='app')
self.cur = db.cursor()
def get_data(self):
sql = "SELECT * FROM foobar"
self.cur.execute(sql)
rs = self.cur
r.fetchall()
return rs
I instantiate the class like so DB = db(). Then, in another class, I will refer to it.
class bleh()
def blarg():
DB.get_data()
With something like this, where would I close the cursor and connection? Or am I approaching this completely wrong?
db.close() for connection and cur.close() for cursor.
http://mysql-python.sourceforge.net/MySQLdb.html
EDIT:
But if it give it a bit thought - you won't need to close cursor. Python closes the cursor once the variable is destroyed, so when the instance of your class does not exist anymore -- cursor will be closed.
First of all use different names for class-name and variable as you have used same name ('db') for class-name and connection as well.
Next, you need to define conn (in your question db line no 3) as self.conn.
import MySQLdb
class db():
def __init__(self):
self.conn = MySQLdb.connect(host='mysql.server', user='user', passwd='pass', db='app')
self.cur = self.conn.cursor()
def get_data(self):
sql = "SELECT * FROM test"
self.cur.execute(sql)
rs = self.cur
rs.fetchall()
return rs
class bleh()
def blarg():
data = DB.get_data()
DB.cur.close()
DB.conn.close()
Note: If you have multiple functions in class bleh to get data from database make sure that you close cursor and connection in function, which is to called in last. Or you may have a seperate function, which closes cursor and connection.