When I query my MySQL Database I get some extra characters that I don't want.
For example, instead of getting 165 I get (165), so, I tried the following in order to extract the number.
The problem is that instead of getting only the number, my code will print nothing, I can't find the reason. Any advice?
arr = ''
num = re.findall('\d+', arr)
mydb = mysql.connector.connect(
host="localhost",
user="root",
database="diff"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
myresult = mycursor.fetchall()
for x in myresult:
arr = x
print(arr)
something like this maybe:
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="Bellini10-",
database="diff"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
myresult = mycursor.fetchall()
pattern = re.compile("\d+")
for x in myresult:
num = pattern.findAll(x)[0]
print(num)
most Python database connectors I've used give back tuples, you'd thus want to do:
for (x,) in myresult:
print(x)
and you should get what you want
the docs I get suggest you can also just the cursor an iterable context manager, thus something like:
with mydb.cursor() as cur:
cur.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
for (x,) in cur:
print(x)
would be more idiomatic Python
Try this:
whitelist = set('0123456789')
num = ''.join(filter(whitelist.__contains__, arr))
Hope this helps!
Related
Newby working my way through python and sql with mariadb.
Why wont this loop? It updates the first record only. Im pretty hack at this...
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
else:
result = 1
upd_data=(result,rid)
sql1 = ("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s")
cursor2.execute(sql1,upd_data)
conn.commit()
Since you are fetching multiple rows you have to store the fetched values in an array and use cursor's executemany() method instead.
✂
data= []
for x in records:
rid = (x[0])
result= int(x[1] > x[2])
data+= [(result, rid)]
cursor.executemany(UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s", data);
✂
When using mariadb python module (MariaDB Connector/Python) this is much more effective since it reduces network traffic: instead of sending n update commands in a loop (where n is the number of rows in table pumped) only one command will be send to the server.
conn = msql.connect(host=Host,port=Port, user=User, password=Password, database=database)
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()
else:
result = 1
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()
I trying to get separate strings from a column in a table. If I output them without anything they are looking like this:
('https://google.com',)
('http://example.com',)
('http://example.com,http://google.cpm',)
('http://example.com, http://google.cpm',)
('google.com, example.cpm',)
('google.com,example.com',)
('google.com, google.com',)
I want to check all off them with a function, if they are online or offline.
Here is my current script:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
database="python1"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT test1 FROM test2")
myresult = mycursor.fetchall()
for x in myresult:
x = .split(",")
return x
print(x)
I dont know how to fix this.
Thanks in advance
If you're trying to write a function that returns the parts of the names as individual items, you can do that:
def getUrls(mydb):
mycursor = mydb.cursor()
mycursor.execute( "SELECT test1 FROM test2" )
for row in mycursor.fetchAll():
for part in row[0].split(','):
yield part
I am building a POS (point of sale) in python with MySQL!
I want to list all articles, but I get the JSON-like output.
My code:
import mysql.connector
print('eXperience POS\nArtikli:')
posdb = mysql.connector.connect\
(
user='root',
password='',
host='127.0.0.1',
database='experiencepos'
)
try:
cursor = posdb.cursor()
cursor.execute('SELECT * FROM artikli')
sviartikli = cursor.fetchall()
print(sviartikli)
finally:
posdb.close()
I think you're confusing JSON output with it printing a dict. Each item in the cursor returns a dict containing the item's fields. Since you did not show the example output I'll just use a name and description field for example. This is what I think you're looking for though. Also you may want to just loop through the cursor as printing the entire cursor would just print a list of dicts with all the items.
import mysql.connector
print('eXperience POS\nArtikli:')
posdb = mysql.connector.connect\
(
user='root',
password='',
host='127.0.0.1',
database='experiencepos'
)
try:
cursor = posdb.cursor()
cursor.execute('SELECT * FROM artikli')
for sviartikli in cursor:
name = sviartikli['name'] #example field
description = sviartikli['description'] #another example field
print("Name: {} Description: {}")
finally:
posdb.close()
from sqlalchemy import create_engine
engine = create_engine('mssql+pymssql://myusername:mypassword#127.0.0.1:1433/AQOA_Core')
connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
for row in result:
print row[0]
connection.close()
The above code returns a result set as:
FRANCETV
GAUMONT
M6SND
PATHE
STUDIOCANAL
TF1
WARNER
What if I want to print just one value without changing the query?
Tried print row[0][1], print row[0:1] This was tried to print just the first value FRANCETV
Basically I want to be able to print each one of the values in the result set seperately without making changes to the query.
You can try to access the data by:
connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
result_list = result.fetchall()
result_list[0][0]
connection.close()
If you take a look at the pymssql docs, you'll see the cursor object has a fetchone() method.
with engine.connect() as connection:
cursor = connection.cursor()
cursor.execute("""SELECT DISTINCT Distributor FROM Product""")
first_row = cursor.fetchone()
print first_row
file = open("testfile.txt", "w", encoding='utf-8')
mycursor.execute('SELECT * from COMPANY')
myresult = mycursor.fetchall()
counter = 0
y = 0
for x in myresult:
y = 0
while y < 3:
print(y)
file.write("%s\n" % myresult[counter][y])
y = y + 1
counter = counter + 1
file.close()
This is what I concluded from the answers above
Writing a script to clean up some data. Super unoptimized but this cursor is
returning the number of results in the like query rather than the rows what am I doing wrong.
#!/usr/bin/python
import re
import MySQLdb
import collections
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="admin", # your username
passwd="", # your password
db="test") # name of the data base
# you must create a Cursor object. It will let
# you execute all the query you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM vendor")
seen = []
# print all the first cell of all the rows
for row in cur.fetchall() :
for word in row[1].split(' '):
seen.append(word)
_digits = re.compile('\d')
def contains_digits(d):
return bool(_digits.search(d))
count_word = collections.Counter(seen)
found_multi = [i for i in count_word if count_word[i] > 1 and not contains_digits(i) and len(i) > 1]
unique_multiples = list(found_multi)
groups = dict()
for word in unique_multiples:
like_str = '%' + word + '%'
res = cur.execute("""SELECT * FROM vendor where name like %s""", like_str)
You are storing the result of cur.execute(), which is the number of rows. You are never actually fetching any of the results.
Use .fetchall() to get all result rows or iterate over the cursor after executing:
for word in unique_multiples:
like_str = '%' + word + '%'
cur.execute("""SELECT * FROM vendor where name like %s""", like_str)
for row in cur:
print row