Get list without JSON-like style mysql python - 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()

Related

How can i iterate through multiple DBs in python to SQL? is there a better way to do it than pyodbc.connect?

ZMDB counter has multiple DBs stored in a list, and i want each to be passed through to Database using .format or some other method to iterate through DBs
import pyodbc
x = []
def NMDretrievefunc():
for each in ZMDBCounter(): #tells the list to pass in the database name below, each DB in the list
conn = pyodbc.connect('Driver={SQL Server};'
'Server=alm-zm-sql;'
'Database={};'.format(each)#each is the DB name within the list
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM [dbo].[InstNonMaturityDetail]')
for i in cursor:
x.append(i)
return x
I found the answer
instead of
'Database={};'.format(each)#each is the DB name within the list
use
' f'Database={each};''

Get separated string with a comma from a table

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

How to load column names from Amazon Redshift with Psycopg? [duplicate]

So currently when I execute SELECT query and retrieve data I have to get results like this:
connection = psycopg2.connect(user="admin",
password="admin",
host="127.0.0.1",
port="5432",
database="postgres_db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM user")
users = cursor.fetchall()
for row in users:
print(row[0])
print(row[1])
print(row[2])
What I want to do is, use column names instead of integers, like this:
for row in users:
print(row["id"])
print(row["first_name"])
print(row["last_name"])
Is this possible, and if it is, then how to do it?
You need to use RealDictCursor, then you can access the results like a dictionary:
import psycopg2
from psycopg2.extras import RealDictCursor
connection = psycopg2.connect(user="...",
password="...",
host="...",
port="...",
database="...",
cursor_factory=RealDictCursor)
cursor = connection.cursor()
cursor.execute("SELECT * FROM user")
users = cursor.fetchall()
print(users)
print(users[0]['user'])
Output:
[RealDictRow([('user', 'dbAdmin')])]
dbAdmin
no need to call fetchall() method, the psycopg2 cursor is an iterable object you can directly do:
cursor.execute("SELECT * FROM user")
for buff in cursor:
row = {}
c = 0
for col in cursor.description:
row.update({str(col[0]): buff[c]})
c += 1
print(row["id"])
print(row["first_name"])
print(row["last_name"])

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

Using Python to write to HTML file with MySQL data as source?

I am trying to generate some simple html pages that contain data stored in a MySQL database. I have searched and searched for an answer to this and while I can successfully generate html pages from txt or user input I can't get it working with SQL. I am not worried about formatting the data in html or anything, that I can work out. All I would like to do is something like the following but I can't work out how to actually get the data printing to the file. Any help would be greatly appreciated.
import MySQLdb
def data():
db_connection = MySQLdb.connect(host='localhost', user='root', passwd='')
cursor = db_connection.cursor()
cursor.execute('USE inb104')
cursor.execute("SELECT Value FROM popularity WHERE Category = 'movies'")
result = cursor.fetchall()
return result
htmlFilename = 'test.html'
htmlFile = open(htmlFilename, 'w')
htmlFile.write = data
htmlFile.close()
def data():
db_connection = MySQLdb.connect(host='localhost', user='root', passwd='')
cursor = db_connection.cursor()
cursor.execute('USE inb104')
cursor.execute("SELECT Value FROM popularity WHERE Category = 'movies'")
result = cursor.fetchall()
return ' '.join(result)
If your data() returns a tuple, you may want to use join to make it into a string.
Change this:
htmlFile.write = data
to:
def formatDataAsHtml(data):
return "<br>".join(data)
htmlFile.write(formatDataAsHtml(data()))
Make sure to replace
return ' '.join(result)
with
list_of_strings = ["(%s)" % c for c in result]
return ' '.join(list_of_strings)

Categories

Resources