this error comes suddenly , i am sure the tables exists in database cause it was works nicely after that i dont know wht happnd the window couldn't shown up to me :
Traceback (most recent call last):
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\app.py", line 71, in <module>
window=MainWindow()
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\app.py", line 12, in __init__
self.depts=Departments.get_all_depts()
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\departments.py", line 18, in get_all_depts
result= cur.execute(sql).fetchall()
sqlite3.OperationalError: no such table: departments
this is departments.py :
from sqlite3 import connect
class Departments:
def __init__(self,dept_id,dept_name,location_id):
self.dept_id=dept_id
self.dept_name=dept_name
self.location_id=location_id
def __repr__(self):
return self.dept_name
#staticmethod
def get_all_depts():
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql= 'SELECT * FROM departments'
result= cur.execute(sql).fetchall()
result=[Departments(*row)for row in result]
return result
def saveToDb(self):
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql='INSERT INTO departments VALUES (:dept_id , :dept_name , :location_id)'
cur.execute(sql,self.__dict__)
conn.commit()
def deleteFromDb(self):
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql='DELETE FROM departments WHERE department_id = :dept_id'
cur.execute(sql,self.__dict__)
conn.commit()
and here app.py when i run it the error above shown up:
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *
from main_window import Ui_Form
from departments import Departments
from locats import locates
from emloyee import Employee
class MainWindow(QWidget,Ui_Form):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
self.depts=Departments.get_all_depts()
self.load_depts()
self.emps= Employee.get_all_emps()
self.load_emps()
self.cb_depts.currentIndexChanged.connect(self.select_depts)
self.le_search.textChanged.connect(self.search)
self.bt_add_dept.clicked.connect(self.show_add_depts_dialog)
self.bt_del_dept.clicked.connect(self.delet_dept)
def load_depts(self):
dept_names= [d.dept_name for d in self.depts]
self.cb_depts.addItems(dept_names)
def load_emps(self):
self.tb_emps.setRowCount(0)
for i,e in enumerate(self.emps):
self.tb_emps.insertRow(i)
for n,v in enumerate(e.__dict__.values()):
self.tb_emps.setItem(i,n,QTableWidgetItem(str(v)))
def select_depts(self,idx):
self.load_emps()
if idx !=0:
dept_i=self.depts[idx-1]
for i,e in enumerate(self.emps):
if e.dept_id != dept_i.dept_id:
self.tb_emps.hideRow(i)
def search(self):
self.load_emps()
text=self.le_search.text()
if text != "":
for i,e in enumerate (self.emps):
if not e.emp_name.startswith(text):
self.tb_emps.hideRow(i)
def show_add_depts_dialog(self):
dialog = loadUi("C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\add_depts.ui")
locs={str(l.location_id) for l in self.depts}
dialog.cb_locats.addItems(locs)
choice =dialog.exec()
if choice ==1:
dept = Departments(dialog.le_deps_id.text(),
dialog.le_deps_name.text(),
dialog.cb_locats.currentText())
self.depts.append(dept)
self.cb_depts.addItem(dept.dept_name)
dept.saveToDb()
def delet_dept(self):
idx=self.cb_depts.currentIndex()
if idx != 0:
self.cb_depts.removeItem(idx)
dept = self.depts.pop(idx-1)
dept.deleteFromDb()
app = QApplication([])
window=MainWindow()
window.show()
app.exec()
employee.py:
from sqlite3 import connect
class Employee:
def __init__(self,emp_id,emp_name,email,hire_date,job_id,salary,dept_id):
self.emp_id=emp_id
self.emp_name=emp_name
self.email=email
self.hire_date=hire_date
self.job_id=job_id
self.salary=salary
self.dept_id=dept_id
def __repr__(self):
return self.emp_name
#staticmethod
def get_all_emps():
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql= 'SELECT employee_id,last_name,email,hire_date,job_id,salary,department_id FROM employees'
result= cur.execute(sql).fetchall()
result=[Employee(*row)for row in result]
return result
tables are already existed i take screen shoot:
enter image description here
any help pls????????????????????????????????????????????????????
Related
When I am trying to call Db cursor method from DbConnection.py class it is saying in execute method call line the following. I want to call Db curson from Database class and use it in any python class. Here I want to use it in Review.py. From Database end table is present in the database.
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "d:\Python\Report-monitoring-system\com\acc\report\main\Main.py", line 33, in <lambda>
review = ttk.Button(name="",text="Review",command=lambda: reviewObj.reviewReport(self.program),style="C.TButton")
File "D:\Python/Report-monitoring-system\com\acc\report\report\review\Review.py", line 25, in reviewReport
print(sqlCursor.execute("SELECT * FROM edp_report"))
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\cursor_cext.py", line 232, in execute
if not self._cnx:
ReferenceError: weakly-referenced object no longer exists
Here's my code below,
DbConnection.py
class DbConnection:
def getConnection(self):
myDb = mysql.connector.connect(
host="localhost",
user = "root",
password = "#####",
database = "edp_report_vision"
)
return myDb.cursor(buffered=True)
Review.py
class Review:
# Report Display Window
def reviewReport(self,program):
if (program!=None):
print("Not null")
win = Toplevel(program)
win.title("New Window")
win.geometry("626x431")
style = ttk.Style()
dbConnection = DbConnection()
# print(dbConnection.getConnection)
sqlCursor = dbConnection.getConnection()
if (dbConnection.getConnection!=None):
print("Db not null")
print(sqlCursor.execute("SELECT * FROM edp_report"))
style.configure("BW.TLabel", foreground="black", background="white")
l1 = ttk.Label(win,text="Test1", style="BW.TLabel")
l2 = ttk.Label(win,text="Test", style="BW.TLabel")
l1.pack()
else:
print("Null")
else:
print("Program null")
Also Main class,this is the invoking class
Main.py
class Main:
program = Tk()
def Show_Page(self):
# program = Tk()
self.program.title("My Tkinter app")
style = ttk.Style()
style.map("C.TButton",
foreground=[('pressed', 'red'), ('active', 'blue')],
background=[('pressed', '!disabled', 'black'), ('active', 'white')]
)
self.program.geometry("626x431")
reviewObj = Review()
monitor = ttk.Button(name="",text="Monitor",command=self.selectReports,style="C.TButton")
monitor.pack(pady=100)
review = ttk.Button(name="",text="Review",command=lambda: reviewObj.reviewReport(self.program),style="C.TButton")
review.pack(pady=0)
self.program.mainloop()
# Main method
if __name__ == "__main__":
objectMain = Main()
objectMain.Show_Page()
As myDb is a local variable inside getConnection(), so it will be garbage collected after the function exits.
My suggestion is to change myDb to instance variable and initialize it inside __init__() instead:
class DbConnection:
def __init__(self):
self.myDb = mysql.connector.connect(
host="localhost",
user = "root",
password = "#####",
database = "edp_report_vision"
)
def getConnection(self):
return self.myDb.cursor(buffered=True)
I was wondering how to display information from an database table onto a listwidget or something similar. This is for a flashcard app, and the one questions is supposed to show at a time. Then when the click to reveal button is clicked the corresponding answer is supposed to show, but at the moment nothing is shown in the list widgets.
I don't understand why nothing is being shown in the GUI.
Here is my Code -
from PyQt4 import QtGui
from PyQt4 import QtCore
import sys
import flashcard
import os
import sqlite3
class FlashCardApp(QtGui.QMainWindow, flashcard.Ui_MainWindow):
def __init__(self):
super(self.__class__,self).__init__()
self.setupUi(self)
self.questions = []
self.answers = []
self.currentQ = 0
self.RevealAnswerBtn.clicked.connect(self.disA)
def dispQ(self):
print("display question {}".format(self.currentQ+1))
self.listQuestionWidget.clear()
if self.questions:
self.listQuestionWidget.addItem(self.questions[self.currentQ])
def disA(self):
self.listAnswerWidget.clear()
if self.answers:
self.listAnswerWidget.addItem(self.answers[self.currentQ])
def setData (self, questions, answers):
self.questions = questions
self.answers = answers
def run(self):
print ("start")
self.currentQ = 0
self.dispQ()
def main():
questions = []
answers = []
connection = sqlite3.connect("login.db")
c = connection.cursor()
c.execute ("SELECT Question FROM Flashcards")
resultq = c.fetchall()
questions.append(resultq)
c.execute ("SELECT Answer FROM Flashcards")
resulta = c.fetchall()
answers.append(resulta)
connection.close()
app = QtGui.QApplication(sys.argv)
form = FlashCardApp()
form.setData(questions,answers)
form.run()
form.show()
app.exec_()
if __name__ == '__main__':
main()
but then i get this error -
Traceback (most recent call last):
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 68, in <module>
main()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 63, in main
form.run()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 41, in run
self.dispQ()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 25, in dispQ
self.listQuestionWidget.addItem(self.questions[self.currentQ])
TypeError: arguments did not match any overloaded call:
QListWidget.addItem(QListWidgetItem): argument 1 has unexpected type 'list'
QListWidget.addItem(str): argument 1 has unexpected type 'list'
I am trying to convert my script into a class, Since I will be using the connect method everytime,
I want to place it in the constructor, and then call it in the other functions.
I am new classes in Python, This is a
from datetime import date
import pymssql
import sys
class PHQuery:
def __init__(self):
self.conn = self.conn()
def get_stock_by_sku(self, sku):
if self.conn["code"] < 0:
return {"code":-1,"error":conn["error"]}
cursor = self.conn.cursor(as_dict=True)
try:
cursor.execute('''
SELECT NUMBER, UNITS, LOW, UNCOST, PRICE1, ONORDER
FROM STOCK
WHERE NUMBER=%s''', sku)
return {"code":1,"data":cursor.fetchone()}
except Exception as e:
return {"code":-2,"error":e}
def conn(self):
try:
conn = pymssql.connect(server='server', user='user', password='pwd', database='db', timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, port='1433')
return {"code":1,"data":conn}
except Exception as e:
return {"code":-1,"error":e}
OUTPUT ERRORS:
File "test.py", line 3, in
print testObject.get_stock_by_sku('BK31')
TypeError: unbound method get_stock_by_sku() must be called with PHQuery instance as first argument (got str instance instead)
THIS IS THE CALL TO THE METHOD
from query import PHQuery
testObject = PHQuery
print testObject.get_stock_by_sku('BK31')
Here is my goal
data = {"stock_id" : "12345"}
qobject = PHQuery()
qobject.get_stock_by_sku(data["stock_id"])
and return the same data my script returns:
The script below is working perfectly fine, I just need to make it a class.
THANK YOU IN ADVANCE.
WORKING CODE:
import time
from datetime import date
import pymssql
import sys
def conn():
try:
conn = pymssql.connect(server='', user='', password='', database='', timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, port='1433')
return {"code":1,"data":conn}
except Exception as e:
return {"code":-1,"error":e}
conn = conn()
def get_stock_by_sku(conn,sku):
""" Returns stock information when passing a sku"""
if conn["code"] < 0:
return {"code":-1,"error":conn["error"]}
cursor = conn["data"].cursor(as_dict=True)
try:
cursor.execute('''
SELECT NUMBER, UNITS, LOW, UNCOST, PRICE1, ONORDER
FROM STOCK
WHERE NUMBER=%s''', sku)
return {"code":1,"data":cursor.fetchone()}
except Exception as e:
return {"code":-2,"error":e}
I'm trying to create a Collection Class in Python to access the various collections in my db. Here's what I've got:
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
client = MongoClient()
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
# self.data_base = getattr(self.client, db)
# self.collObject = getattr(self.data_base, self.collection_name)
def getCollection(self):
data_base = getattr(self.client, self.db)
collObject = getattr(data_base, self.collection_name)
return collObject
def getCollectionKeys(self, collection):
"""Get a set of keys from a collection"""
keys_list = []
collection_list = collection.find()
for document in collection_list:
for field in document.keys():
keys_list.append(field)
keys_set = set(keys_list)
return keys_set
if __name__ == '__main__':
print"Begin Main"
agents = Collection('hkpr_restore','agents')
print "agents is" , agents
agents_collection = agents.getCollection
print agents_collection
print agents.getCollectionKeys(agents_collection)
I get the following output:
Begin Main
agents is <__main__.Collection instance at 0x10ff33e60>
<bound method Collection.getCollection of <__main__.Collection instance at 0x10ff33e60>>
Traceback (most recent call last):
File "collection.py", line 52, in <module>
print agents.getCollectionKeys(agents_collection)
File "collection.py", line 35, in getCollectionKeys
collection_list = collection.find()
AttributeError: 'function' object has no attribute 'find'
The function getCollectionKeys works fine outside of a class. What am I doing wrong?
This line:
agents_collection = agents.getCollection
Should be:
agents_collection = agents.getCollection()
Also, you don't need to use getattr the way you are. Your getCollection method can be:
def getCollection(self):
return self.client[self.db][self.collection_name]
I guys, I developing a utility in python and i have 2 object the main class and an database helper for get sqlserver data.
database.py
import _mssql
class sqlserver(object):
global _host, _userid, _pwd, _db
def __new__ (self, host, userid, pwd, database):
_host = host
_userid = userid
_pwd = pwd
_db = database
def GetDataStore(self, sql):
conn = _mssql.connect(server='(local)\\sqlexpress', user='sa', password='xxx', database='Framework.Data2')
conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))')
conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')")
conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')")
gaemodel.py
import os
import sys
from fwk import system, types, databases
class helper(object):
pass
def usage(app_name):
return "Usage: %s <project name>" % (app_name)
def main(argv):
_io = system.io()
project_name = argv[1]
project_home = os.path.join(_io.CurrentDir(), project_name)
_db = databases.sqlserver('(local)\sqlexpress', 'sa', 'xxx', 'Framework.Data2')
_db.GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'")
str = "from google.appengine.ext import db"
#for row in cur:
# str += "class %s" % row["name"]
print cur
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1:])
else:
print usage(sys.argv[0]);
My problem is when i try run code return me this error
Traceback (most recent call last):
File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 28, in <module>
main(sys.argv[1:])
File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 18, in main
_ db. GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'")
AttributeError: 'NoneType' object has no attribute 'GetDataStore'
What is wrong ??
First of all:
The __new__ method should be named __init__.
Remove the global _host etc. line
Then change the __init__ method:
self.host = host
self.userid = userid
etc.
And change GetDataStore:
conn = _mssql.connect(server=self.host, user=self.userid, etc.)
That should do the trick.
I suggest you read a bit on object-oriented Python.
Have a look at what __new__ is supposed to be doing and what arguments it's supposed to have. I think you wanted to use __init__ and not __new__. The reason for your particular error is that _db is None.
I think you want to change databases.py like this:
import _mssql
class sqlserver(object):
def __init__ (self, host, userid, pwd, database):
self.host = host
self.userid = userid
self.pwd = pwd
self.db = database
def GetDataStore(self, sql):
conn = _mssql.connect(server=self.host, user=self.userid, password=self.pwd, database=self.db)
conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))')
conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')")
conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')")