Elements from database not deleted - python

I am currently creating a program using SQLite3. While entries can be added to this database, I cannot seem to be able to delete them.
import database
db_actions = database.DatabaseActions()
def set_delete_student_parameters():
del_student_number = delete_number_enter
DeleteStudent(del_student_number)
def DeleteStudent(del_student_number):
db_actions.delete_student(del_student_number)
import sqlite3
my_conn = sqlite3.connect('general_db.db')
print("Connected to database successfully")
class DatabaseActions:
def __init__(self):
self.db = sqlite3.connect('general_db.db') # Open database connection here
self.setup_tables()
def delete_student(self, student_number):
cursor = self.db.cursor()
sql = "DELETE FROM Students WHERE StudentNumber=?"
cursor.execute(sql, [str(student_number)])
self.db.commit()

Related

Can I get dictionary from pymysql?

I have a following question. I would like to get content of a table in dictionary format. My code:
from configparser import ConfigParser
import pymysql as mysql
class Database:
def __init__(self):
config = ConfigParser()
config.read("config.ini")
user = config["db"]["user"]
passwd = config["db"]["password"]
host = config["db"]["host"]
db = config["db"]["database"]
self.connection = mysql.connect(
user=user,
passwd=passwd,
host=host,
db=db,
)
self.cursor = self.connection.cursor()
def init_dict(self):
query = """
SELECT a, b
FROM mytable
"""
self.cursor.execute(query)
data = self.cursor.fetchall()
return dict(data)
Is there a more pythonic way how to get data in the method init_dict as a dictionary? I found, that it should be possible to return a dict directly from the cursor, but I don`t know how. Thanks a lot.

Use multiple functions in MySQLdb (python)

this code below runs just fine, but i want to separate this code into function (this is my first time using MySQLdb) ,
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","user_name","pass","db_name" )
cursor = db.cursor()
sql = "SELECT activity_log.datetime FROM activity_log"
cursor.execute(sql)
date_data = cursor.fetchall()
for content in date_data:
print content
# disconnect from server
db.close()
Question: how could I create one database connection and use it to multiple functions, this is what i've wrote so far (doesn't work):
import MySQLdb
class DB():
def __init__(self):
db = MySQLdb.connect("locahost", "user_name", "pass", "db_name")
self.cur = db.cursor()
def time_statistic(self):
sql = "SELECT activity_log.datetime FROM activity_log"
self.cur.execute(sql)
self.date_data = self.cursor.fetchone()
for content in self.date_data:
print content
def test1(self):
pass
if __name__ == '__main__':
db = DB.connect("db_name" )
db.time_statistic(self)
db.test1(self)
db.close()
You need to pass the arguments to init to make sure that the class connects to the right DB.
import MySQLdb
class DB():
def __init__(self, server, user, password, db_name):
db = MySQLdb.connect(server, user, password, db_name)
self.cur = db.cursor()
def time_statistic(self):
sql = "SELECT activity_log.datetime FROM activity_log"
self.cur.execute(sql)
self.date_data = self.cursor.fetchone()
for content in self.date_data:
print content
def test1(self):
pass
if __name__ == '__main__':
db = DB(<server>, <user>, <password>, <db_name>)
db.time_statistic()
db.test1()
Replace the arguments in <> with actual values you need to connect to the db. You may also want to add some error handling in the above code.

Unable to execute Postgres queries in Python

I'm trying to create a Postgres table using psycopg2 in Python as follows:
import psycopg2
class DbOperations (object):
def __init__(self):
self.dummy = None
self.conn = None
self.cur = None
self.query = None
self.db_name = "alarm_log"
self.table_name = "alarms"
self.user = "cayman"
self.password = "admin"
self.host = "127.0.0.1"
def db_connect(self):
self.conn = psycopg2.connect(dbname=self.db_name, user=self.user, password=self.password, host=self.host)
self.cur = self.conn.cursor()
def db_disconnect(self):
self.conn.close()
def db_create_table(self):
self.query ="""
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
"""
print (self.query)
self.cur.execute(self.query)
Then I construct the object as follows:
db_app = DbOperations()
db_app.db_connect()
db_app.db_create_table()
I am able to manually connect to the database and create the table. However, I'm not able to do so using Python.
There are no exceptions or error messages. When I try to list the tables in the database manually, I don't find my newly created table.
Any suggestions what could be wrong ?
Seems, you are missing the commit at the end of db_create_table method:
self.conn.commit()
Iron Fist's answer is absolutely correct, but if you don't want to have commits all over your code, you can also set it on the connection like this:
def db_connect(self):
self.conn = psycopg2.connect(dbname=self.db_name, user=self.user, password=self.password, host=self.host)
self.conn.autocommit = True
self.cur = self.conn.cursor()

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 2.7 connection string to PostgreSQL (OOP method)

I'm new to python and I'm trying to make this work. I'm using Python 2.7 and PostgreSQL 9.3:
#! F:\Python2.7.6\python
import psycopg2
class Database:
host = "192.168.56.101"
user = "testuser"
passwd = "passwd"
db = "test"
def __init__(self):
self.connection = psycopg2.connect( host = self.host,
user = self.user,
password = self.passwd,
dbname = self.db )
self.cursor = self.connection.cursor
def query(self, q):
cursor = self.cursor
cursor.execute(q)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
q = "DELETE FROM testschema.test"
db.query(q)
However I am getting an error "AttributeError: 'builtin_function_or_method' object has no attribute 'execute'". I figure I should put something like self.execute = something in the Database class, but I can't figure it out what exactly I need to put there. Any suggestions?
You are missing the parenthesis at the end
self.cursor = self.connection.cursor()
or
cursor = self.cursor()
But not both

Categories