PSP class import + MySQL connect - python

Ok so im trying to import a class i made which connects to a MySQL database the class code is shown below:
class connection
def__init__( self ):
self.cnx = MySQLdb.connect(user='xxx',host='xxx',passwd='xxx',db='xxx')
All of the parameters for the mysql connection are correct and file containg the class is in the same directory as the PSP file. The class file is called cnx_class.py
when i run my PSP file i get 'cnx' isnt defined. My psp code is below:
<psp:file>
import cnx_class
</psp:file>
<%
cur = cnx.cursor()
cur.execute('select * from protein;')
rows = cur.fetchall()
for row in rows:
req.write`(row)`
#end
%>
any help?

You are horribly, horribly confused as to how modules and classes work. Please read and work through at least the modules section and the classes section of the Python tutorial.

Try replacing
cur = cnx.cursor()
with
con=cnx_class.connection()
cur=con.cnx.cursor()
You can also replace
rows = cur.fetchall()
for row in rows:
with
for row in cur.fetchall():
since cursors are iterators.

Related

How to call cursor.execute if the connection "with" and "cur" are in another different py file?

Having self.con = sqlite3.connect (db) and self.cur = self.con.cursor() in the db.py file, how can I call them in the main.py file to use cursor.execute? I wrote db.self.cur.execute('SELECT Name FROM TableExample'), but obviously I was wrong, there is an error of course
P.S: In db.py do I have to insert the path of the database inside db of the sqlite3.connect(db)?
I had tried like this:
DB.PY
import sqlite3
class Database:
def __init__(self, db):
self.con = sqlite3.connect(db)
self.cur = self.con.cursor()
sql = """
CREATE TABLE IF NOT EXISTS employees(
ID Integer Primary Key,
example1 integer,
example2 integer
)
"""
self.cur.execute(sql)
self.con.commit()
MAIN.PY
from db import Database
db = Database('/home/xxxx/database.db')
def example():
db.self.cur.execute('SELECT Name FROM TableExample') #error
result=[row[0] for row in cursor]
return result
UPDATE: New example in main.py
def example():
db.cur.execute('SELECT Name FROM TableExample')
result=[row[0] for row in db.cur]
return result
There are a few problems to fix here. The error on this line:
db.self.cur.execute('SELECT Name FROM TableExample') #error
is because of the use of self. You'll want to read up on how to use classes, but in short self (named that by convention, not requirement) is how an object instance refers to itself, such as where you set self.cur in __init__(). You don't refer to self outside the object.
Instead, you want to refer to the cur attribute of the db object like this:
db.cur.execute('SELECT Name FROM TableExample')
The next issue is the list expression that reads from the database. This:
result=[row[0] for row in cursor]
is going to cause an error, because cursor is not defined. You probably want to refer to the cur attribute in the db object:
result=[row[0] for row in db.cur]
However, while this works, it's not the best way to do it. You're implicitly using the results of the last query executed on the cursor, which does work, but is less obvious.
Better would be to create a new cursor object from the query and iterate that:
query = db.cur.execute('SELECT Name FROM TableExample')
result = [row[0] for row in query]

SQL and Python - using a variable in an SQL statement

import sqlite3
conn = sqlite3.connect('troubleshooting.db')
cur = conn.cursor()
user = input("hello")
for row in cur.execute('SELECT user FROM problems WHERE user = %s'):
print(row)
My problem here is that the variable 'user' is only being read as text and not changing occurring to what I name it (user = input("hello")). How do I change it so it does read it as a variable (please keep it simple, I am a beginner when it comes to programming).
Thanks for helping out :)

instance has no attribute (python)

I have a weird issue, which is probably easy to resolve.
I have a class Database with an __init__ and an executeDictMore method (among others).
class Database():
def __init__(self, database, server,login, password ):
self.database = database
my_conv = { FIELD_TYPE.LONG: int }
self.conn = MySQLdb.Connection(user=login, passwd=password, db=self.database, host=server, conv=my_conv)
self.cursor = self.conn.cursor()
def executeDictMore(self, query):
self.cursor.execute(query)
data = self.cursor.fetchall()
if data == None :
return None
result = []
for d in data:
desc = self.cursor.description
dict = {}
for (name, value) in zip(desc, d) :
dict[name[0]] = value
result.append(dict)
return result
Then I instantiate this class in a file db_functions.py :
from Database import Database
db = Database()
And I call the executeDictMore method from a function of db_functions :
def test(id):
query = "SELECT * FROM table WHERE table_id=%s;" %(id)
return db.executeDictMore(query)
Now comes the weird part.
If I import db_functions and call db_functions.test(id) from a python console:
import db_functions
t = db_functions.test(12)
it works just fine.
But if I do the same thing from another python file I get the following error :
AttributeError: Database instance has no attribute 'executeDictMore'
I really don't understand what is going on here. I don't think I have another Database class interfering. And I append the folder where the modules are in sys.path, so it should call the right module anyway.
If someone has an idea, it's very welcome.
You have another Database module or package in your path somewhere, and it is getting imported instead.
To diagnose where that other module is living, add:
import Database
print Database.__file__
before the from Database import Database line; it'll print the filename of the module. You'll have to rename one or the other module to not conflict.
You could at least try to avoid SQL injection. Python provides such neat ways to do so:
def executeDictMore(self, query, data=None):
self.cursor.execute(query, data)
and
def test(id):
query = "SELECT * FROM table WHERE table_id=%s"
return db.executeDictMore(query, id)
are the ways to do so.
Sorry, this should rather be a comment, but an answer allows for better formatting. Iam aware that it doesn't answer your question...
You should insert (not append) into your sys.path if you want it first in the search path:
sys.path.insert(0, '/path/to/your/Database/class')
Im not too sure what is wrong but you could try passing the database object to the function as an argument like
db_functions.test(db, 12) with db being your Database class

using python 2.7 to query sqlite3 database and getting "sqlite3 operational error no such table"

My simple test code is listed below. I created the table already and can query it using the SQLite Manager add-in on Firefox so I know the table and data exist. When I run the query in python (and using the python shell) I get the no such table error
def TroyTest(self, acctno):
conn = sqlite3.connect('TroyData.db')
curs = conn.cursor()
v1 = curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
print v1
conn.close()
When you pass SQLite a non-existing path, it'll happily open a new database for you, instead of telling you that the file did not exist before. When you do that, it'll be empty and you'll instead get a "No such table" error.
You are using a relative path to the database, meaning it'll try to open the database in the current directory, and that is probably not where you think it is..
The remedy is to use an absolute path instead:
conn = sqlite3.connect('/full/path/to/TroyData.db')
You need to loop over the cursor to see results:
curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
for row in curs:
print row[0]
or call fetchone():
print curs.fetchone() # prints whole row tuple
The problem is the SQL statment. you must specify the db name and after the table name...
'''SELECT * FROM db_name.table_name WHERE acctno = ? '''

Creating Python Module using pyodbc

want to make small python module that can get data from a database. I have dowload pydbc and it worked fine like this:
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
Now i want to put this in a module so that i can import it and i dont need to write the code evrytime or locate the file. So i tried to create this like this
import pyodbc
def testDB():
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
return row
I saved it in: File "C:\Python27\lib\site-packages\testDB.py" and i tried to import it, but i got this error: SyntaxError: 'return' outside function
Im quite new to python, any ideas how i can put this as a module and be able to use import everytime i want to run that code?
As one of the comments says, your indentation is messed up. White space (indentation) is critical in Python. Try it like this:
import pyodbc
def testDB():
cnxn = pyodbc.connect("DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''")
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
return row
Also, you have to use double quotes for your connection string, since you are using single quotes in the string itself. I've changed them above in to reflect that.
good luck,
Mike

Categories