Python clipping database returned variables - python

I'm busy with a script to get some data from the database and arrange it for output later and I would like to know how to clip the variables being returned
I have my script
# CONNECT TO DATABASE
#=====================================================================
varPgSQL = connectToDatabase()
# PREPARE SQL STATEMENTS
#=====================================================================
cur_users = varPgSQL.cursor()
cur_users.execute("prepare cur_users as " +
"select * from users " +
"where usr_idno > $1")
cur_details = varPgSQL.cursor()
cur_details.execute("prepare cur_details as " +
"select * from details " +
"where dtl_usr_idno = $1")
# EXECUTE SQL STATEMENTS
#=====================================================================
la_results = []
cur_users.execute("execute cur_users(%s)", str(0))
for lr_user in cur_users:
cur_details.execute("execute cur_details(%s)", str(lr_user[0]))
for lr_detail in cur_details:
# STORE RESULTS
la_results.append({
"usr_idno": lr_user[0],
"usr_name": lr_user[1],
"dtl_usr_idno": lr_detail[0],
"dtl_usr_accn": lr_detail[1],
"dtl_usr_accs": lr_detail[2]
})
# CLOSE CONNECTION
#=====================================================================
varPgSQL.close()
# CHECK RESULTS
#=====================================================================
for lr_result in la_results:
print(
" | " +
lr_result["usr_name"] +
" | " +
lr_result["dtl_usr_accn"] +
" | " +
lr_result["dtl_usr_accs"] +
" | "
)
The output of this code though is not clipping the variables, the output is
| mavis | service acc | active |
Which is what I expected because it's the length of the fields in the database but is it possible to clip the variables for output to achieve
| mavis | service acc | active |

If the gaps are being created by whitespace you can use the built in String method strip()
If its is a database artifact you may have to give us more information.

Related

Updating database script can't process quotations ( 'x' )

I have been struggling to update a record. I need to update a record with the following query:
UPDATE TRIPSHEETDETAILS
SET MAIL_OFD = 1
WHERE DELNO = '0000204258'
Where I am struggling is that DELNO needs to be in between quotations. ( 'x' )
One of two things will happen it will stop halfway and not complete the run or it will run and not update.
I have tried the following:
mycur.execute("UPDATE TRIPSHEETDETAILS
"set MAIL_OFD = 1 "
"where DELNO = '" + array[x][1] + "'" )
>array[x][1] will be the value 0000204258 that is in string
sql = "UPDATE TRIPSHEETDETAILS SET MAIL_OFD = 1 WHERE DELNO = '%s'"
val = ("0000204258")
mycur.execute(sql, val)
a = '0000204258'
mycur.execute(
"UPDATE TRIPSHEETDETAILS "
"SET MAIL_OFD = 1 "
" where DELNO = '" + a + "'"
)
When doing the folloing it works; which shows me the concept of it works.
mycur.execute(
"""UPDATE TRIPSHEETDETAILS SET MAIL_OFD = 1 WHERE DELNO = '0000204258'"""
)
Something to note. If I change the DELNO to something else that does not require the quotations ('') then it works. However I would prefer to use DELNO.

I was creating a bot to snipe hypixel api discord bot but its creating a error by channel.send_message ,

done = default_timer() - START_TIME
if op:
winsound.Beep(500, 500) # emits a frequency 500hz, for 500ms
for result in results:
profit = result[1] - result[0][2]
print("/viewauction " + str(result[0][0]) + " | Item Name: " + str(result[0][1]) + " | Item price: {:,}".format(result[0][2]) + " | Profit : {:,}".format(profit) + " | Time to refresh AH: " + str(round(done, 2)))
print('\x1b[6;30;42m' + 'Sniping Auctions :)' + '\x1b[0m')
channel = client.get_channel(954629794224566302)
channel.send_message("/viewauction " + str(result[0][0]) + " | Item Name: " + str(result[0][1]) + " | Item price: {:,}".format(result[0][2]) + " | Profit : {:,}".format(profit) + " | Time to refresh AH: " + str(round(done, 2)))
This code is not very helpful and provide the error message.
btw channel.send_message() is replaced with channel.send()

How to have a python script print out the exact match in a txt file?

I have a python script that takes user input, then searches a txt file and prints the line. However, when the user inputs a number that is apart of other numbers it will print out everything in relation.
For example, if the user inputs STT1, but there is another line thats called STT12, 13, 14 etc. The script prints out each line since it has the number 1 in it. How would do I make the script only print out the exact match?
Example Output
Please enter your area: TTT17
Please enter STT name: STT1
STT Location:
TTT17 | STT1 | Floor 1 | Row 2 | Section 2
STT Location:
TTT17 | STT13 | Floor 1 | Row 22 | Section 2
STT Location:
TTT17 | STT14 | Floor 1 | Row 22 | Section 2
STT Location:
TTT17 | STT17 | Floor 1 | Row 42 | Section 2
STT Location:
TTT17 | STT18 | Floor 1 | Row 42 | Section 2
Example Code
def find_stt():
with open('{}'.format(db_file), 'r') as f:
find_flag = False
for line in f.readlines():
if line.startswith(area) and name in line:
print("\n" + "\n" + "\n" + color.BOLD + "STT Location:" + color.END +
"\n" + "\n" + color.BOLD + ' '.join(line.split()) + color.END + "\n")
find_flag = True
if not find_flag:
failed_search()
You are checking with name in line. This condition will be true for all the substrings that contain name. Using regular expression will be a solution for this.
if line.startswith(area) and re.search(r'\b'+ name + r'\b', line)
I was able to figure it out. May not be the best way, but it works. Basically I took my input variable,
name = input("Please enter STT name: ").upper()
and created a new variable with it adding a space at the end
name_search = name + " "
def find_stt():
with open("{}".format(db_file), "r") as f:
find_flag = False
for line in f.readlines():
if line.startswith(area) and name_search in line:
print("\n" + "\n" + "\n" + color.BOLD + "SPP Location:" + color.END +
"\n" + "\n" + color.BOLD + " ".join(line.split()) + color.END +
"\n")
find_flag = True
if not find_flag:
failed_search()
This resolved my issue.

Dynamically passing the column name as well the values in python mysql query

This is the following code
pythonlist = ['Name','Mno']
datalist = ["qwerty",'234']
sql = "SELECT " + ",".join(pythonlist) + " FROM data WHERE name = '"+ "','".join(datalist) + "' INTO OUTFILE filename"
print(sql)
OUTPUT:
SELECT Name,Mno FROM data WHERE Name= 'qwerty','234'
DESIRED OUTPUT:
SELECT Name,Mno FROM data WHERE Name = 'qwerty' and Mno = 234
Do note the removal of quotations marks in 'mno'.
The reason I am doing this is due because the column names, as well as values corresponding it to, will change frequently
Code :
queryparams = {'Name': 'qwerty', 'Mno': '234'}
and_clause = []
[and_clause.append(' %s = %s ') for k,v in queryparams.items()]
and_clause_str = ' and '.join(and_clause)
sql = 'SELECT %s FROM data WHERE ' + and_clause_str
params = [','.join(queryparams.keys())]
for k,v in queryparams.items():
params.append(str(k))
params.append(str(v))
print(sql)
print(params)
cursor.execute(sql, params=tuple(params))
This works if you add 10/20 more items to dictionary .
Aswell as prevents SQL-injection : Using params to pass values instead of string-concatenation .
Try this:
data = {'Name': 'qwerty' , 'Mno' : '234'}
sql = "SELECT " + ", ".join(data.keys()) + " FROM data WHERE " + str(list(data.keys())[0]) + " = '" + \
str(data[list(data.keys())[0]]) + "' and " +\
str(list(data.keys())[1]) + " = " + str(data[list(data.keys())[1]])
print(sql)

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 "

Categories

Resources