I want to connect a QComboBox with SQL Server.
I'm creating an employee form, where the user can add the data for each employee. I want to use 3 tables (already made and populated in SQL Server) for the QComboBox, one for the Building, one for the Department and one for the Job. The problem is that I can't figure out how to do it.
I've used some code that I found online, which is the following:
self.deptcombbox = QComboBox()
self.deptcombbox.addItems(self.deptcomb)
and
def deptcomb(self):
conn = pyodbc.connect("DRIVER={SQL Server};SERVER=DESKTOP-QFV3HFM\SQLEXPRESS;DATABASE=Tests;USERNAME=ggs;PASSWORD=2332")
q = conn.cursor()
q.execute('SELECT DISTINCT dept_name FROM departments')
pmList = q.fetchall()
pmList = list(pmList)
conn.commit()
conn.close()
return pmList
but I get error:
Traceback (most recent call last):
File "c:\Users\gnsta\Documents\Programming tests\EmployeeForm.py", line 89, in <module>
window = Window()
File "c:\Users\gnsta\Documents\Programming tests\EmployeeForm.py", line 24, in __init__
self.buildingcombobox.addItems(self.buildcomb)
TypeError: addItems(self, Iterable[str]): argument 1 has unexpected type 'method'
I understand that I need to use a list for the combobox, but list() isn't working.
Related
I am pretty new to Python and trying to use a very simple one table DB.
I'm using python 3, peewee and pymysql. The database is MySQL, local on my Windows 10 PC (wampserver) and the code is;
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import peewee
from peewee import *
db = MySQLdb.connect(user='xxxxx', passwd='xxxxx',
host='localhost', port=3306, db='xxxxx')
class SearchUrl(peewee.Model):
id = peewee.AutoField()
url = peewee.TextField()
page_title = peewee.TextField()
date_found = peewee.DateField()
date_last_changed = peewee.DateField()
article_status = peewee.CharField()
description = peewee.TextField()
class Meta:
database = db
newUrl = SearchUrl.create(url='http://cropnosis.co.uk', page_title="Cropnosis Ltd.",
date_found='2018-04-13', status='new', description='Cropnosis website')
newUrl.save()
for url in SearchUrl.filter(url='http://cropnosis.co.uk'):
print(url.description)
db.close()
Whenever I run this I get the following error in the "SearchUrl.create" line. I have searched for the 'returning_clause' attribute but have found little or no mention of it esp. with regard to MySQL.
Any help or relevant links greatly appreciated.
Traceback (most recent call last):
File "researcherDb.py", line 26, in <module>
date_found='2018-04-13', status='new', description='Cropnosis website')
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5161, in create
inst.save(force_insert=True)
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5284, in save
pk_from_cursor = self.insert(**field_dict).execute()
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5128, in insert
return ModelInsert(cls, cls._normalize_data(__data, insert))
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5868, in __init__
if self.model._meta.database.returning_clause:
AttributeError: 'Connection' object has no attribute 'returning_clause'
You want this:
from peewee import *
# this is peewee.MySQLDatabase, not pymysql's connection class.
db = MySQLDatabase('the_db_name', user='xxxxx', passwd='xxxxx')
I'm working on an application and currently focusing on the database area.
I have successfully setup functions that create databases and write to them, however right now I am trying to retrieve specific rows from the database however NO MATTER WHAT I TRY I always get a syntax error DESPITE my SQL query running successfully in in sqlite browser.
This is my trouble code:
def findapple():
conn = sqlite3.connect('working.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM "working" WHERE "symbol" = 'aapl';')
print row
If I understand the code I've written, it should connect to "working.db" create a cursor for the database then for each row that match my query it should be printed to the console.
Can anyone please help shed some light on this?
Thank you!
Current Code Per comments below:
def findapple():
conn = sqlite3.connect('working.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM working WHERE symbol = 'aapl'')
print row
and the error output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
from stock import *
File "/Users/ME/Documents/Code/Stocks/stock/database.py", line 61
for row in c.execute('SELECT * FROM working WHERE symbol = 'aapl'')
Your string syntax is wrong:
c.execute('SELECT * FROM working WHERE symbol = "aapl"')
Hello I am having a bit of a dumbo problem. I am trying to search a DB for an ID number. The problem I am running into in when I enter a ID number that does not exist the program crashes. I will post my code under and try to explain where I am at. I am using SQlite with Python3.
cur = con.cursor()
cur.execute("SELECT * FROM coupons WHERE id_num=:id_num",
{"id_num": input_value})
con.commit()
row = cur.fetchone()
#Verifying that the ID exists for later in the program.
if input_value == row[0]:
bad_code = False
I know my programming is somewhat amateurish but I am still learning the ropes.
The error is as follows:
Traceback (most recent call last):
File "Z:/Python_Programs/data_bases/coupon_scanner_v8.py", line 217, in <module>
verify_barcode(user_code);
File "Z:/Python_Programs/data_bases/coupon_scanner_v8.py", line 87, in verify_barcode
startDay = row[1]
TypeError: 'NoneType' object is not subscriptable
I will continue to do research to solve this problem. Thank you!!!
fetchone() returns None if there are no more values to fetch from the cursor - in your case, where the id doesn't exist. So, in order to check if the id existed you should do something down these lines:
row = cur.fetchone()
# Verifying that the ID exists for later in the program.
if row is not None:
bad_code = False
I get the following error code while executing my Code. The error does not occur immediately - it occurs randomly after 2-7 hours. Until the error occurs there is no problem to stream the online feeds and write them in a DB.
Error message:
Traceback (most recent call last):
File "C:\Python27\MySQL_finalversion\RSS_common_FV.py", line 78, in <module>
main()
File "C:\Python27\MySQL_finalversion\RSS_common_FV.py", line 63, in main
feed_iii = feed_load_iii(feed_url_iii)
File "C:\Python27\MySQL_finalversion\RSS_common_FV.py", line 44, in feed_load_iii
in feedparser.parse(feed_iii).entries]
IndexError: list index out of range
Here you can find my Code:
import feedparser
import MySQLdb
import time
from cookielib import CookieJar
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username - SELECT * FROM mysql.user
passwd="****", # your password
db="sentimentanalysis_unicode",
charset="utf8") # name of the data base
cur = db.cursor()
cur.execute("SET NAMES utf8")
cur.execute("SET CHARACTER SET utf8")
cur.execute("SET character_set_connection=utf8")
cur.execute("DROP TABLE IF EXISTS feeddata_iii")
sql_iii = """CREATE TABLE feeddata_iii(III_ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(III_ID),III_UnixTimesstamp integer,III_Timestamp varchar(255),III_Source varchar(255),III_Title varchar(255),III_Text TEXT,III_Link varchar(255),III_Epic varchar(255),III_CommentNr integer,III_Author varchar(255))"""
cur.execute(sql_iii)
def feed_load_iii(feed_iii):
return [(time.time(),
entry.published,
'iii',
entry.title,
entry.summary,
entry.link,
(entry.link.split('=cotn:')[1]).split('.L&id=')[0],
(entry.link.split('.L&id=')[1]).split('&display=')[0],
entry.author)
for entry
in feedparser.parse(feed_iii).entries]
def main():
feed_url_iii = "http://www.iii.co.uk/site_wide_discussions/site_wide_rss2.epl"
feed_iii = feed_load_iii(feed_url_iii)
print feed_iii[1][1]
for item in feed_iii:
cur.execute("""INSERT INTO feeddata_iii(III_UnixTimesstamp, III_Timestamp, III_Source, III_Title, III_Text, III_Link, III_Epic, III_CommentNr, III_Author) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)""",item)
db.commit()
if __name__ == "__main__":
while True:
main()
time.sleep(240)
If you need further information - please feel free to ask. I need your help!
Thanks and Regards from London!
In essence, your program is insufficiently resilient to poorly-formatted data.
Your code makes very explicit assumptions about the structure of the data, and is unable to cope if the data is not so structured. You need to detect the cases where the data is incorrectly formatted and take some other action then.
A rather sloppy way to do this would simply trap the exception that's currently being raised which you could do with (something like)
try:
feed_iii = feed_load_iii(feed_url_iii)
except IndexError:
# do something to report or handle the data format problem
I am a programming beginner, and would like to get a little help with learning SQLite and Python.
Currently, I have a database called "Status.db" which contains two columns. These columns are "stamp", type INT, and "messages", type TEXT, consecutively.
The code I am using to try to read one instance of messages, with a particular stamp, ID, into a variable "output" is as follows:
#cherrypy.expose
def comment(self, ID = None):
con = lite.connect('static/database/Status.db')
with con:
cur = con.cursor()
cur.execute("SELECT messages FROM Status WHERE stamp is ?", (ID,))
temp = cur.fetchone()
output = temp[0]
However, when i execute this code, I get an error message that reads:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "proj1base.py", line 176, in comment
output = temp[0]
TypeError: 'NoneType' object is not subscriptable
I am wondering if anyone could clarify to me what this error means, and what i could do to make it work.
Thanks in advance!
EDIT:
Here is the code that created and writes into the database
#cherrypy.expose
def writeStatus(self, newStatus=None, post=None):
"""Update the status file with the most recent status update
by inserting a timestamp and new status into a database
"""
con = lite.connect('static/database/Status.db')
stamp = time()
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Status(stamp INT, messages TEXT)")
cur.execute("INSERT INTO Status VALUES(?, ?)", (stamp, newStatus))
That means that fetchone() is returning None, which means that your SQL query isn't returning any result rows.
This is probably because you should use = instead of is in your SQL:
SELECT messages FROM Status WHERE stamp = ?