INSERT INTO not working. Unique Constraint Failed (Python SQLite) - python

I am creating a sorting application that picks students out of a table and puts them in form groups. Gender should be equal across the groups. It loops through each table inserting random male students.
I have used print functions to track what is happening. It seems like the loop is working since
print(idMale)
is printing rows out. However there hasn't been an insertion at all in the other table. And the program breaks and outputs this error:
.
Here is my code:
# loops through each table
for x in range(0,groupNumber):
#Adds I to table name to go through each table
nameGroupList.append('I')
print(nameGroupList)
nameGroup = ''.join(nameGroupList)
#loop to select a student from the main table (sessionName) and insert them into another group
#loop number is subject to the number of males that should be in 1 group
for x in range(0, formMaleInt):
selectMaleRow = cur.execute("SELECT * FROM " + sessionName + " WHERE Gender='M' ORDER BY random() Limit 1")
#-----Find ID of student selected so they can be deleted from sessionName
idMale = selectMaleRow.fetchone()
print(idMale)
idSepChar = list(idMale)
idNum = idSepChar[0]
idNumStr = str(idNum)
#-----Find ID of student selected so they can be deleted from sessionName
insertMaleRow = cur.execute("INSERT INTO " + nameGroup + " SELECT * FROM " + sessionName + " WHERE Gender='M' ORDER BY random() Limit 1")
deleteMaleRow = cur.execute("DELETE FROM " + sessionName + " WHERE ID='" + idNumStr + "'")
Here is my sessionName table:
Here is my other table

Related

How can I avoid SQL DB2 issue?

When I run this query by manually it execute correctly without any issue and I can get the store number and item number but when I use it in my framework and connect my scenario step to the Db2 it gives me an error. This is the query which one is I execute:::
cursor.execute("select * from qs36f.DSTHSTP join qs36f.calendar on date_ccyymmd = dhindt where date_iso between(current date - 10 day) and current date and DHCUS# in (" + open_stores + ") and dhqtss>=1 and DHCLSS = " + class_nbr + " and dhsbcl = " + sub_class_nbr + " and ((dhqtss*dhrt5s)*DHPACK) <" + end_range + "")
I don't know what is the issue here. This is error:::
cursor.execute("select * from qs36f.DSTHSTP join qs36f.calendar on date_ccyymmd = dhindt where date_iso between(current date - 10 day) and current date and DHCUS# in (" + open_stores + ") and dhqtss>=1 and DHCLSS = " + class_nbr + " and dhsbcl = " + sub_class_nbr + " and ((dhqtss*dhrt5s)*DHPACK) <" + end_range + "")
pyodbc.ProgrammingError: ('42000', '[42000] [IBM][System i Access ODBC Driver][DB2 for i5/OS]SQL0104 - Token , was not valid. Valid tokens: FOR USE SKIP WAIT WITH FETCH LIMIT ORDER UNION EXCEPT OFFSET. (-104) (SQLExecDirectW)')
My expectations is I have to retrieve from database store number and item number.
It seems you are facing a syntax error. Having that your statement is:
select *
from qs36f.DSTHSTP
join qs36f.calendar
on date_ccyymmd = dhindt
where date_iso between (current date - 10 day) and current date
and DHCUS# in (" + open_stores + ")
and dhqtss>=1
and DHCLSS = " + class_nbr + "
and dhsbcl = " + sub_class_nbr + "
and ((dhqtss*dhrt5s)*DHPACK) <" + end_range + "
It's possible that you are not building it correctly. In such cases, try to remove one line from the WHERE clause and execute the query in order to find the one that is not correct.

Insert into an unknown mysql column

Am trying to insert values into a mysql table with unknown database columns that are present in the db but can be found - and are passed - from inside a loop, however I am still stuck and I get the error message. I have written sample code that reproduces the error and tries to generate the mysql query dynamically. Is there a simpler way to do this with mysql? Why is my code not running? The final query seems correct
Error
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s,%s,%s,%s)' at line 1
The far that I could imagine
from Learn.callmysql import mycursor, db
datte = {}
datte["schoolfee"] = "amount"
datte["student"] = "name"
testlist = ["parent", "bothnames"] #Notte this will be generated dynamically so I have no idea the variables in it, this is a sample
thelist = []
secondlist = ""
for value in testlist:
datte[value] = "Bch" #here "Bch will be a real unknown value"
print("Final dictionary after adding degree is like: " + str(datte))
for value in datte:
thelist.append(value)
breakdown = "("
count = 0
total_count_should_be = len(thelist)
for value in thelist:
if count == total_count_should_be -1:
breakdown = breakdown + value + ")"
else:
breakdown = breakdown + value+","
count = count + 1
first_part_of_query = breakdown
print("First part of the query will be like: " + first_part_of_query)
for index in range(len(thelist)):
if index == 0:
secondlist = secondlist + "(%s,"
elif index == len(thelist)-1:
secondlist = secondlist + "%s)"
else:
secondlist = secondlist + "%s,"
second_part_of_the_query = secondlist
print("Second part of the query will be like: " + second_part_of_the_query)
#Try to join the queries
query = "INSERT INTO testtale " + first_part_of_query + " VALUES " + second_part_of_the_query
print("Query looks like: " + query)
val = datte
mycursor.execute(query, val)
db.commit()
CODE PRINTS
As #Rob Streeting suggested,
I have converted my dictionary into an ordered list then to a tuple like so
print("Dictionary is: " + str(datte))
list = []
for value in datte.values():
list.append(value)
listintotupple = tuple(list)
print(listintotupple)
Then passed it to the query:
#Try to join the queries
query = "INSERT INTO testtale " + first_part_of_query + " VALUES " + second_part_of_the_query
print("Query looks like: " + query)
val = listintotupple
mycursor.execute(query, val)
db.commit()

Python store value from SQL request into a variable

this is the code I have in Python:
for y in cursor.fetchone():
# for test - print current product attribute ID
print("Updated at Id_product_attribute: " + str(y))
# I want to select ID stock based on Id_product_attribute
idStockAvailble = "SELECT id_stock_available FROM ps_stock_available WHERE id_product_attribute = " + str(y) + ";"
cursor.execute(idStockAvailble)
# for test - print stock ID
print("Id stock availble: " + str(idStockAvailble))
When I print "idStockAvailble" i get:
Id stock availble: SELECT id_stock_available FROM ps_stock_available WHERE id_product_attribute = 136;
How can I get the value of "id_stock_available "

How to introduce a switch breaker to perform insert every 50 lines

My current code basically does a bulk insert after iterating around all of the rows in my excel file. I want to introduce a switch breaker that will perform the insert every 50 lines.
db = Database(settings)
elt_insert_line = "INSERT INTO elt_data VALUES"
for row in r:
elt_insert_line = elt_insert_line + "(" + row[2] + ", " + row[3] + "),"
db.execute(elt_insert_line.rstrip(",")).commit().cleanup()
Using modulo operator and IF conditional
not familiar with python but i think you need something like this
db = Database(settings)
elt_insert_line = "INSERT INTO elt_data VALUES"
for row in r:
elt_insert_line = elt_insert_line + "(" + row[2] + ", " + row[3] + "),"
if r % 50 = 0 then
(
db.execute(elt_insert_line.rstrip(",")).commit().cleanup()
elt_insert_line = "INSERT INTO elt_data VALUES"
)
--one aditional at the end of the for
db.execute(elt_insert_line.rstrip(",")).commit().cleanup()

Using data from a website, match it to a table and pull data

After hours and hours of looking around and reading documents, I have to call for help and sanity. I'm no python expert or even HTML expert, so I'd appreciate every small bit of help that I can get.
I can pay for a little time if needed...
What I'm trying to do is:
Two webpages. One is in my server and one isn't. The one that isn't in my server (order.asp), has this line:
<FONT CLASS="fv">Estimated Weight of Order:</FONT></TD><TD ALIGN="RIGHT"><FONT CLASS="fv">XX.XXoz XX.XXg</FONT>
I need something that I can put in my server, queries the weight from the page that isn't on my server (order.asp page) and matches the weight with a shipping price that I would have on my page (as a table or maybe with ifs).
There will be different order pages (order1.asp order2.asp order3.asp) with different weights. The script or whatever should do that for ea. wpage.
Here's a flowchart I just made to help understand:
http://www.gliffy.com/go/publish/image/5123674/L.png
A very helpful user already gave me this piece of code:
html = open("html.txt").read()
out = open("foundWeights.txt", "w")
#split html on order number
legoOrders = html.split("Order #")
for order in legoOrders[1:]:
print order
orderNumber = order.split("<")[0]
weightString = order.split('Estimated Weight of Order:</FONT></TD><TD ALIGN="RIGHT"><FONT CLASS="fv">')[1]
splitWeightString = weightString.split(' ')
splitStringFinal = splitWeightString[1].split("<")
grams = splitStringFinal[0]
ozs = weightString.split('&nbsp')[0]
out.write(str(orderNumber) + "\t" + str(grams) + "\t" + str(ozs) + "\n"
Which pulls out the order number, and weight in ozs and grams.
What I don't know how to do is, having a table of shipping prices and weight ranges, match that weight to a shipping price, pull the shipping price and... well, do some things with it.
Ideally, if I knew how to do that (I don't know nothing in python, but I do know programming basics and C), I could pull the order total too, sum the order total and the shipping price, and FINALLY get a grand total.
I hope I made it clear.
All the best,
Gerald
This is how the page order.asp will look like (varying the weight and order total numbers):
http://pastebin.com/uH18CF5k
Getting there slowly. I added this to your code #duhaime
#get Shipping Range
test = "B"
if ( 0 < grams < 100 ):
test = "A"
if ( 100 < grams < 500):
test = "A"
Along with the str(test) in the out.write.
However, it prints a B when I run it, but it should print an A. Know what's wrong?
Thanks again for your feedback, #Brick Top. This code pulls down the Order Number, Grand Total, Order Total, Shipping Cost, Weight in Grams, and Weight in Ozs from the html, and writes them to a tab-separated text file that you can open and easily review in Excel.
EDIT: The script also calculates the shipping class, based on the weight of the order in grams. The Shipping Class is indicated in the final column of the out file:
from decimal import *
html = open("html.txt").read()
out = open("legoShipping.txt", "w")
out.write("Order Number" + "\t" +
"Grand Total (currency)" + "\t" +
"Order Total (currency)" + "\t" +
"Shipping Cost (currency)" + "\t" +
"Order Weight (grams)" + "\t" +
"Order Weight (oz.)" + "\t" +
"Shipping Class" + "\n")
#split html on order number
legoOrders = html.split("Order #")
for order in legoOrders[1:]:
orderNumber = order.split("<")[0]
#get Grand Total
grand = order.split("<TD>Grand Total:</TD>")[1].split('<TD ALIGN="RIGHT"><B>')[1].split("<")[0].split(' ')
grandCurrency = grand[0]
grandTotal = grand[1]
#get Order Total
orderTotalAndCurrency = order.split('<TD>Order Total:</TD>')[1].split('<TD ALIGN="RIGHT">')[1].split("<")[0].split(' ')
orderCurrency = orderTotalAndCurrency[0]
orderTotal = orderTotalAndCurrency[1]
#get Shipping Cost
shipping = order.split("<TD>Shipping:</TD>")[1].split('<TD ALIGN="RIGHT">')[1].split("<")[0].split(' ')
shippingCurrency = shipping[0]
shippingCost = shipping[1]
#get Weights
weightString = order.split('Estimated Weight of Order:</FONT></TD><TD ALIGN="RIGHT"><FONT CLASS="fv">')[1]
splitWeightString = weightString.split(' ')
splitStringFinal = splitWeightString[1].split("<")
grams = splitStringFinal[0]
ozs = weightString.split('&nbsp')[0]
#convert grams to mathematical value
gramsValue = Decimal(grams[:-1])
#create default shipping class value. Set it to ""
shippingClass = ""
if gramsValue > 0:
if gramsValue < 100:
shippingClass = "A"
if gramsValue >= 100:
if gramsValue < 200:
shippingClass = "B"
out.write(str(orderNumber) + "\t" +
str(grandTotal) + " (" + str(grandCurrency) + ")" + "\t" +
str(orderTotal) + " (" + str(orderCurrency) + ")" + "\t" +
str(shippingCost) + " (" + str(shippingCurrency) + ")" + "\t" +
str(grams) + "\t" +
str(ozs) + "\t" +
str(shippingClass) + "\n")
Output in OpenOffice Calc:

Categories

Resources