Get separated string with a comma from a table - python

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

Related

Python and MySQL - fetchall() doesn't show any result

I have a problem getting the query results from my Python-Code. The connection to the database seems to work, but i always get the error:
"InterfaceError: No result set to fetch from."
Can somebody help me with my problem? Thank you!!!
cnx = mysql.connector.connect(
host="127.0.0.1" ,
user="root" ,
passwd="*****",
db="testdb"
)
cursor = cnx.cursor()
query = ("Select * from employee ;")
cursor.execute(query)
row = cursor.fetchall()
If your problem is still not solved, you can consider replacing the python mysql driver package and use pymysql.
You can write code like this
#!/usr/bin/python
import pymysql
db = pymysql.connect(host="localhost", # your host, usually localhost
user="test", # your username
passwd="test", # your password
db="test") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
query = ("SELECT * FROM employee")
# Use all the SQL you like
cur.execute(query)
# print all the first cell of all the rows
for row in cur.fetchall():
print(row[0])
db.close()
This should be able to find the result you want
add this to your code
for i in row:
print(i)
you did not print anything which is why that's not working
this will print each row in separate line
first try to print(row),if it fails try to execute using the for the loop,remove the semicolon in the select query statement
cursor = connection.cursor()
rows = cursor.execute('SELECT * FROM [DBname].[dbo].TableName where update_status is null ').fetchall()
for row in rows:
ds = row[0]
state = row[1]
here row[0] represent the first columnname in the database
& row[1] represent the second columnname in the database & so on

how to connect MySQL database to input function

I'm building a program, where the user input an enterprise's name to get the code running.
I would like the user to pick the enterprise name in a drop down list, but currently i dont have a GUI to make it work.
so for now, I would like to connect the input function to the SQL database enterprises name column.
I already connected SQL to my python code... but how do I connect MySQL to an input function? I want the user to be able to get the information from the database
MY SQL CONNECTION :
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM listedatabase.entreprises_inspecteurs")
for row in mycursor.fetchall():
print (row[1])
mydb.close()
python:
enterprise_name = input()
Thank you for helping
I tried this but no luck:
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
enterprise_name = input()
mycursor.execute("SELECT n_fabricant FROM listedatabase.entreprises_inspecteurs", (enterprise_name,))
data = mycursor.fetchall()
if data:
code goes there
else:
print('data not found in database')
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
enterprise_name = input()
mycursor.execute("""SELECT n_fabricant FROM listedatabase.entreprises_inspecteurs WHERE n_fabricant = %s"""(event_inspecteur,))
data = mycursor.fetchall()
if data:
code goes there
else:
print('data not found in database')

adding data to arrays in python with for loops from sql data return

I'm trying to add data to an array inside a loop as each row is column and row is returned.
my objective is to sort the columns into a few arrays but this does not appear to be working. i;ve been googling all afternoon about how to do this in python. W3 schools is demonstrating something like this but it wont work, nor will their simple array examples e.g. array[0] = "text" , and keeps returning errors that NameError: 'ReturnedUser_id' is not defined.
I then wish to pass these arrays out once i turn this code into a function.
Can anyone help me?
Thanks
import mysql.connector
mydb = mysql.connector.connect(
import mysql.connector
mydb = mysql.connector.connect(
host="xxx.xxx.xxx.xxx",
user="xxxxxxx",
passwd="xxxxxx",
database="vmware"
)
print(mydb)
mycursor = mydb.cursor()
mycursor.execute("select UserID, VMName, VMTemplate FROM VM WHERE CommissionStatus='commissioned';")
c = 0
for (User_id, VMName, VMTemplate) in mycursor:
c += 1
ReturnedUser_id[c] = User_id
ReturnedVMName[c] = VMName
ReturnedVMTemplate[c] = VMTemplate
To solve your problem with the current architecture you need to replace your logic with:
ReturnedUser_id = []
ReturnedVMName = []
ReturnedVMTemplate = []
for (User_id, VMName, VMTemplate) in mycursor:
ReturnedUser_id.append(User_id)
ReturnedVMName.append(VMName)
ReturnedVMTemplate.append(VMTemplate)
However I would do:
class VM:
def __init__(self, user_id, name, template):
self.user_id = user_id
self.name = name
self.template = template
#staticmethod
def from_row(row):
return VM(row[0], row[1], row[2])
all_vms = []
for row in mycursor:
all_vms.append(VM.from_row(row))
This allows you later to add more fiends and functionality in the VM class and instead of passing around three lists, you only pass one!

Get list without JSON-like style mysql python

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()

Extracting numbers from a string in Python

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!

Categories

Resources