Using fields defined in constructor - Python - python

I have a class as below that I'm using to connect to a remote SQL server instance from a linux server python web app. I define and set cursor in the init constructor and wish to use it throughout the class. How do I do this? I come form a java background and don't understand the scope and protection levels of Python fields.
import pyodbc
class SQLSeverConnection():
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
connection = pyodbc.connect(connectionString)
cursor = connection.cursor()
def getColumnData(self, columnName, tableName):
cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
data = cursor.fetchall()
return data
def getColumnTitles(self, tableName):
cursor.execute('select column_name,* from information_schema.columns where table_name = 'tableName' order by ordinal_position')
columns = cursor.fetchall()
return columns
def getTableNames(self):
cursor.execute('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE''')
tables = cursor.fetchall()
return tables

The answer is simple: Python's "methods" are really plain functions, and local variables are plain local variables. To set / access instance attributes, you must use the current instance, which is passed as first argument to the function (and by convention named self):
class SQLSeverConnection():
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
self.connection = pyodbc.connect(connectionString)
self.cursor = connection.cursor()
def getColumnData(self, columnName, tableName):
self.cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
data = self.cursor.fetchall()
return data
def getColumnTitles(self, tableName):
self.cursor.execute('select column_name,* from information_schema.columns where table_name = 'tableName' order by ordinal_position')
columns = self.cursor.fetchall()
return columns
def getTableNames(self):
BASE_TABLE ='BASE_TABLE'
self.cursor.execute('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'')
tables = self.cursor.fetchall()
return tables
Now using a single shared cursor for all operations is brittle, you'd better instanciate a new cursor for each operation. Also, since a cursor is an iterable, you may want to return the cursor itself and let client code iterate over it, it might save some memory...
class SQLSeverConnection(object):
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
self.connection = pyodbc.connect(connectionString)
def getCursor(self):
return self.connection.cursor()
def getColumnData(self, columnName, tableName):
cursor = self.getCursor()
cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
return cursor
# etc
Oh and yes: using mixCased is not pythonic, we prefer all_lower ;)

change cursor to self.cursor
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
connection = pyodbc.connect(connectionString)
self.cursor = connection.cursor()
def getColumnData(self, columnName, tableName):
self.cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
data = self.cursor.fetchall()
return data

Related

Database creation using python

I am trying to create a database using python. When the program runs no error occurs, however nothing happens. Is there a line I am missing?
class create_db:
def __init__(self):
self.conn = sqlite3.connect("EXAMPLE.db")
self.c = self.conn.cursor()
def create_tables(self, Tables):
for table_name, field in Tables.items():
self.c.execute('CREATE TABLE IF NOT EXISTS ' + table_name + '(' + field + ')')
self.conn.commit()
def main():
db = create_db()
tables = {"CUSTOMERS": '''CustomerID integer,
Customer_Name text,
primary key (CustomerID)'''}
db.create_tables(tables)
main()

Database Error: NameError: name 'db' is not defined. What am I doing wrong?

On the web I found this illustration to create a database with gui with Tkinter. Everything ok, except when I enter the data and click on the Add button. I'm getting:
NameError: name 'db' is not defined
I think what I am wrong is nonsense in this part of the code. What am I doing wrong?
Here is my code uploaded su un editor online. I am writing it here because it is too long to enter. I am new and having difficulty with StackOverflow. If we can figure out the error, I'll update the question with the code I'm wrong.
import sqlite3
conn = sqlite3.connect('/home/dekstop/db.db')
cur = conn.cursor()
class Database:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute(
"CREATE TABLE IF NOT EXISTS routers (id INTEGER PRIMARY KEY, hostname text, brand text, ram integer, flash integer)")
self.conn.commit()
def fetch(self, hostname=''):
self.cur.execute(
"SELECT * FROM routers WHERE hostname LIKE ?", ('%'+hostname+'%',))
rows = self.cur.fetchall()
return rows
def fetch2(self, query):
self.cur.execute(query)
rows = self.cur.fetchall()
return rows
def insert(self, hostname, brand, ram, flash):
self.cur.execute("INSERT INTO routers VALUES (NULL, ?, ?, ?, ?)",
(hostname, brand, ram, flash))
self.conn.commit()
def remove(self, id):
self.cur.execute("DELETE FROM routers WHERE id=?", (id,))
self.conn.commit()
def update(self, id, hostname, brand, ram, flash):
self.cur.execute("UPDATE routers SET hostname = ?, brand = ?, ram = ?, flash = ? WHERE id = ?",
(hostname, brand, ram, flash, id))
self.conn.commit()
def __del__(self):
self.conn.close()
You have this:
import sqlite3
conn = sqlite3.connect('/home/dekstop/db.db')
cur = conn.cursor()
class Database:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute(
"CREATE TABLE IF NOT EXISTS routers (id INTEGER PRIMARY KEY, hostname text, brand text, ram integer, flash integer)")
self.conn.commit()
...
Right away, you can see a problem there. You have conn and curr defined outside the class and inside. It seems clear that the rest of your code expects db to be an instance of the Database class. So you need:
import sqlite3
class Database:
... same as always ...
db = Database('/home/dekstop/db.db')
and you need to do that before any of the code that refers to db.
assigned variable DB not defined. so it raises an error
def add_router():
if brand_text.get() == '' or hostname_text.get() == '' or ram_text.get() == '' or flash_text.get() == '':
messagebox.showerror('Required Fields', 'Please include all fields')
return
db.insert(hostname_text.get(), brand_text.get(),
ram_text.get(), flash_text.get())
clear_text()
populate_list()

UPDATE query by using python

def connect_to_db():
mydb = mysql.connector.connect(
host=CONFIG['host'],
port = CONFIG['port'],
user=CONFIG['username'],
passwd=CONFIG['password'],
database=CONFIG['database']
)
class MyTable:
def __init__(self, conn, table_name):
self.table_name = table_name
self.conn = conn
self.cursor = conn.cursor()
self.commit = conn.commit()
def update(self, whereD, valueD):
if isinstance(whereD, tuple):
where = "%s = '%s'" % whereD
else:
return "error"
kv = ' , '.join(["%s = '%s'" % (k, v) for k, v in valueD.items()])
sql = "UPDATE %s SET %s WHERE %s " % (self.table_name, kv, where)
print(sql)
self.conn
self.cursor
(self.cursor).execute(sql)
self.commit
and I tried to use this class like this:
mydb = connect_to_db()
tab = MyTable(connect_to_db(), "test")
tab.update(('name', 'aaa'), {'age': 800})
The original data is name:aaa, age:20
I connected to mysql by using aws. And I want to use UPDATE query by class MyTable.
But it wasn't worked. Is there something wrong about my code?
cur.execute("Update table set column= ? where cond= ?",[a,b])
You can try this code in update query
Thanks

Need Python Programming Tips

I'm learning python since last few weeks. For better learning, I decided to work on some project. So here is my Class for MySQL connection and demo example as well. Can you please tell me. What other improvement can be possible for following code?
Structure?
What else I can do to optimize code?
And Please forgive. If I'm doing some silly mistakes in code. (I'm learning)
#!/usr/bin/python
import pymysql
# select (table, parameter)
# insert (table, data)
# update (table, id, data)
# delete (table, id)
class MySQL:
def __init__(self):
self.sort_by = ""
self.order = ""
# initiate database connection.
self.connection = pymysql.connect(host='localhost',
user='root',
password='',
db='sherlock',
charset='utf8mb4')
self.cursor = self.connection.cursor(pymysql.cursors.DictCursor)
# this function is for selecting any feild on any table.(feilds veriable is optinal)
def select(self, table, *feilds):
flds = "" #differnt name for feilds veriable.
if not feilds:
flds = '*'
else:
for f in feilds:
if not flds:
flds = f
else:
flds += ",`%s`" % f
sql = "SELECT %s FROM `%s` " % (flds, table)
if self.sort_by:
sql = sql +"order by "+ str(self.sort_by) +" "+ str(self.order)
print sql
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
# This function is for data sorting for Mysql; but optinal.
# example : SELECT * FROM `users` order by id asc
def order_by(self, sort_by="", order="", *args, **kwargs):
self.sort_by = sort_by
self.order = order
# this function is for closing Mysql connection
def close(self):
self.connection.close()
########### END OF MySQL CLASS #############
sql = MySQL()
# sql.order_by function should be called before the sql.select() function.
sql.order_by("email")
# this will select all the feilds from `users` table.
# you can specify whichever feilds you want to return. like : sql.select("users", "id, email")
result = sql.select("users", "password")
for email in result:
print email["password"]
sql.close()

python Sqlite3 parameter subs

I have a small problem with this class which handle my DB. It still saying:
cursor.execute(sql)
ValueError: operation parameter must be str
I tried lots of things but nothing work as i want. I looked over https://docs.python.org/3.4/library/sqlite3.html and i'm sure i do the same things.
import sqlite3
class Database():
def __init__(self):
try:
self.db = sqlite3.connect('../database.sqlite')
self.cur = self.db.cursor()
self.cur.execute('pragma foreign_keys="1"')
except sqlite3.Error as e:
raise e
def select(self,sql):
cursor = self.db.cursor()
cursor.execute(sql)
records = cursor.fetchall()
cursor.close()
return records
def insert(self,sql):
cursor = self.db.cursor()
cursor.execute(sql)
newID = cursor.lastrowid
self.db.commit()
cursor.close()
return newID
def execute(self,sql):
""" execute any SQL statement but no return value given """
cursor = self.db.cursor()
cursor.execute(sql)
self.db.commit()
cursor.close()
if __name__ == '__main__':
db = Database()
#sql = "SELECT skuref, titre_prod FROM product"
t = ("888888",)
sql= "UPDATE product SET created = 1 WHERE skuref = ?", t
db.execute(sql)
If someone can help me it would be grateful.Later i wanted to pass something like this in the main program inside a for loop
lastpost = record[0]
if created = True
sql = "UPDATE product SET created = 1 WHERE skuref = ?",(lastpost,)
db.execute(sql)
sql is a tuple containing SQL statement and the parameters.
Change as following, so that sql and parameters are passed separately, instead of being passed as a tuple:
def execute(self, sql):
""" execute any SQL statement but no return value given """
cursor = self.db.cursor()
cursor.execute(*sql) # <------
self.db.commit()
cursor.close()
With your statement
sql = "UPDATE product SET created = 1 WHERE skuref = ?",(lastpost,)
you have created a tupel like
("UPDATE product SET created = 1 WHERE skuref = ?", (lastpost,))
You have to give the arguments as parameters to the execute() function.
Also your if statement is bad: no :, = instead of == and the whole check for True is no nesesary.
Try this:
lastpost = record[0]
if created:
sql = "UPDATE product SET created = 1 WHERE skuref = ?"
db.execute(sql, lastpost)

Categories