I used the following code to get items from sqlite3 database
def get(self, item_name, attrs=True): #get attr from item and return as dict, if attr==True: get all items
conn = self.conn
if attrs: #all
return conn.execute('SELECT * FROM %s WHERE __item_key__ = "%s";' %(self.table, item_name))
else:
command = 'SELECT '
for attr in attrs:
command+= attr+' '
command+='FROM %s WHERE __item_key__ = "%s";' %(self.table, item_name)
return conn.execute(command)
print(get('name1'))
the code print the following:
<sqlite3.Cursor at 0x213d4c0f490>
instead of the values from the table.
When I try this:
get('name1')[0]
it returns:
TypeError: 'sqlite3.Cursor' object is not subscriptable
Full code:
import sqlite3 as sql
import sqlite3 as sql
class db:
'''
This class turns dicts into sqlite databases
and output sqlite databases as dicts
'''
def __init__(self, db_name, table_name): #open or create a database
conn = sql.connect(db_name).cursor()
self.table = table_name
self.conn = conn
def create(self, table_name, cols):
command = "CREATE TABLE %s(_item_key_ TEXT," % table_name
for key, value in cols.items():
command+="%s %s," %(key, value)
command=command[:-1]
command+=");"
self.conn.execute(command)
self.table = table_name
def get(self, item_name, attrs=True): #get attr from item and return as dict, if attr==True: get all items
conn = self.conn
if attrs: #all
return conn.execute('SELECT * FROM %s WHERE _item_key_ = "%s";' %(self.table, item_name))
else:
command = 'SELECT '
for attr in attrs:
if type(attr) == str:
attr = '"'+attr+'"'
command+= str(attr)+' '
command+='FROM %s WHERE _item_key_ = "%s";' %(self.table, item_name)
return conn.execute(command).fetchall()
def change(self, item_name, attrs): #change certain attrs of item
command = 'UPDATE %s SET ' %self.table
for key, value in attrs:
command += '%s=%s,'%(key, value)
command = command[:-1]+' WHERE _item_name_ = "'+item_name+'";'
def add(self, item_name, attrs): #add an item with attrs to database
command = 'INSERT INTO %s VALUES ("%s",' %(self.table, item_name)
for attr in attrs:
if type(attr) == str:
attr = '"'+attr+'"'
command += str(attr)+','
command = command[:-1]+');'
#print(command)
self.conn.execute(command)
def close(self): #close database
self.conn.close()
The table is supposed to look like the following (although I never saw it):
__item_name__ A B
---------------------------
'name1' 123 'hi'
'name2' 344 'bye'
Does anyone know how this works?
edit: I realized some bugs in create() and add(). However, after fixing some stuff it still prints the same thing in get().
It returns that no cursor object found.
If you want to get the results you need to add these lines:
cur = conn.cursor() # create a cursor to your connection
cur.execute(your_query) # execute your query
results = cur.fetchall() # fetch the results
Also don't forget to iterate over the cursor after results = cur.fetchall():
for row in results:
A = row[0]
B = row[1]
Should revise all code and implement this self.conn.commit() after self.conn.execute(---).
self.conn.execute(command)
self.conn.commit() #<--- THIS NEW line, to after .execute()
self.table = table_name
Related
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
I'm trying to remove a row in SQLite3, on windows it removes the row, but on Ubuntu it won't. I'm not sure what's causing it/how to fix it. Both systems are running Python 3.6.5, and I did not install SQLite3 with pip.
I'm running the following script, which creates a db.sqlite, creates a user table with (key, name) and inserts one user. Then it should remove it:
import sqlite3
class DBHelper:
def __init__(self, dbname="db.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
self.conn.set_trace_callback(print)
def setup(self):
stmt = "CREATE TABLE IF NOT EXISTS users (key text PRIMARY KEY, name text)"
self.conn.execute(stmt)
stmt = "INSERT INTO users (key, name) VALUES ('Acf233146328cea01fe9648acc3053fa', 125368500)"
self.conn.execute(stmt)
self.conn.commit()
def delete_user(self, name, key):
stmt = "DELETE FROM users WHERE name = (?) AND key = (?)"
args = (name, key)
self.conn.execute(stmt, args)
self.conn.commit()
def get_all(self):
stmt = "SELECT name, key FROM users"
return [x for x in self.conn.execute(stmt)]
def get_db():
db = DBHelper()
return db
name = 125368500
key = 'Acf233146328cea01fe9648acc3053fa'
print('Delete {0} {1}'.format(name, key))
db = get_db()
db.setup()
db.delete_user(name, key)
for user_data in db.get_all():
print('{0} {1}'.format(user_data[0], user_data[1]))
On Ubuntu it returns (incorrect):
Delete 125368500 Acf233146328cea01fe9648acc3053fa
CREATE TABLE IF NOT EXISTS users (key text PRIMARY KEY, name text)
BEGIN
INSERT INTO users (key, name) VALUES ('Acf233146328cea01fe9648acc3053fa', 125368500)
COMMIT
BEGIN
DELETE FROM users WHERE name = (125368500) AND key = ('Acf233146328cea01fe9648acc3053fa')
COMMIT
SELECT name, key FROM users
125368500 Acf233146328cea01fe9648acc3053fa
On Windows it returns (correct):
Delete 125368500 Acf233146328cea01fe9648acc3053fa
CREATE TABLE IF NOT EXISTS users (key text PRIMARY KEY, name text)
BEGIN
INSERT INTO users (key, name) VALUES ('Acf233146328cea01fe9648acc3053fa', 125368500)
COMMIT
BEGIN
DELETE FROM users WHERE name = (125368500) AND key = ('Acf233146328cea01fe9648acc3053fa')
COMMIT
SELECT name, key FROM users
Update: So it seems like I'm experiencing a bug introduced in SQLite 3.11.0: https://sqlite.org/src/info/ef360601
And because Ubuntu 16.04.4 LTS comes with 3.11.0 by default I am going to need to update the version.
Update 2: Updating the typings by changing name to string fixes it as well. Seems to be the same case in the sqlite bug report.
Because I was using Ubuntu 16.04 with SQLite it ships with version 3.11.0, which has the following bug: https://sqlite.org/src/info/ef360601
To solve this, I need to use correct types when creating the table/inserting before I can delete the rows.
The fixed code:
import sqlite3
class DBHelper:
def __init__(self, dbname="db.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
self.conn.set_trace_callback(print)
def setup(self):
stmt = "CREATE TABLE IF NOT EXISTS users (key text PRIMARY KEY, name text)"
self.conn.execute(stmt)
stmt = "INSERT INTO users (key, name) VALUES ('Acf233146328cea01fe9648acc3053fa', '125368500')"
self.conn.execute(stmt)
self.conn.commit()
def delete_user(self, name, key):
stmt = "DELETE FROM users WHERE name = (?) AND key = (?)"
args = (name, key)
self.conn.execute(stmt, args)
self.conn.commit()
def get_all(self):
stmt = "SELECT name, key FROM users"
return [x for x in self.conn.execute(stmt)]
def get_db():
db = DBHelper()
return db
name = '125368500'
key = 'Acf233146328cea01fe9648acc3053fa'
print('Delete {0} {1}'.format(name, key))
db = get_db()
db.setup()
db.delete_user(name, key)
for user_data in db.get_all():
print('{0} {1}'.format(user_data[0], user_data[1]))
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()
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)
This is my Bottle code
import sqlite3
import json
from bottle import route, run, request
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def db_connect():
conn = sqlite3.connect('inventory.db')
conn.row_factory = dict_factory
return conn, conn.cursor()
#route('/inventory', method='GET')
def get_inventory():
conn,c=db_connect()
c.execute("SELECT id, name, category, location, date, amount FROM inventory")
result = c.fetchall()
json_result=json.dumps(result)
return json_result
#route('/inventory/get/:id', method='GET')
def get_item(id):
conn,c=db_connect()
c.execute("SELECT id, name, category, location, date, amount FROM inventory WHERE id=?",(id, ))
result=c.fetchall()
json_result=json.dumps(result)
return json_result
#route('/inventory/new', method='POST')
def add_item():
name = request.POST.get('name')
category = request.POST.get('category')
location = request.POST.get('location')
date = request.POST.get('date')
amount = request.POST.get('amount')
conn,c=db_connect()
c.execute("INSERT INTO inventory (name, category, location, date, amount) VALUES (?,?,?,?,?)", (name,category,location,date,amount))
new_id = c.lastrowid
conn.commit()
c.close()
return '<p>The entry with id %d has been added to the database</p>' %new_id
#route('/inventory/delete/:id', method='DELETE')
def delete_item(id):
conn,c=db_connect()
c.execute("DELETE FROM inventory WHERE id =?", (id, ))
conn.commit()
c.close()
return 'The entry with id %s has been deleted from the database' %id
#route('/inventory/edit/:id', method='PUT')
def edit_item(id):
name = request.PUT.get('name')
category = request.PUT.get('category')
amount = request.PUT.get('location')
location = request.PUT.get('date')
date = request.PUT.get('amount')
conn,c=db_connect()
c.execute("UPDATE Inventory SET name=?, category=?, location=?, date=?, amount=? WHERE id=?", (name, category, location, date, amount,id))
conn.commit()
c.close();
return '<p>The entry with id %s has been edited in the database</p>' %id
run(reloader=True)
I am trying to make the make the edit_item method to work.
When I call it with curl
curl -X PUT -d "name=aa&category=bb&amount=23&location=xx&date=21-10-2014" http://localhost:8080/inventory/edit/2
I get a server error which says
raise AttributeError('Atrribute %r is not defined.' % name)
AttributeError: Attribute 'PUT' not defined'
What should i do ?
Instead of this,
name = request.PUT.get('name')
use this:
name = request.params.get('name')