Redshift - Passing output from SQL to different variables - python-3.x

I have a SQL script that extracts sale data by agent.
cur = conn.cursor()
cur.execute("""select sales_rep,to_char(sales_date,'yyyy-mm')as month,count(*) from sale""")
report = cur.fetchall()
I am trying to see if I can pass count obtained from the output to a variable (count) and month value to another variable (month_count).
Could anyone advice on this. Thanks.
Update :
Sample Output:
Sales_Rep,Month,Count
Person1,Jan,20
Person1,Feb,15
Person1,Mar,10
Person2,Jan,8
Person2,Feb,13
Person2,Mar,15
Expected Output:
count = 20,15,108,13,15
month = jan,feb,mar,jan,feb,mar

You just need a basic group by query here:
SELECT
sales_rep,
TO_CHAR(sales_date, 'yyyy-mm') AS month,
COUNT(*) AS cnt
FROM sale
GROUP BY
sales_rep,
TO_CHAR(sales_date, 'yyyy-mm');
Python code:
cur = conn.cursor()
cur.execute("""SELECT sales_rep, TO_CHAR(sales_date, 'yyyy-mm') AS month, COUNT(*) AS cnt FROM sale GROUP BY sales_rep, TO_CHAR(sales_date, 'yyyy-mm')""")
rows = cur.fetchall()
for row in rows:
print("{} " + row["month"]).format(row["cnt"])

Related

Postgres/Python: Executed successfully but no rows inserted

Could somebody pls help me to perform insert operation to postgres database from python?
I have a dataframe:
df_routes
From
To
A
B
B
A
for index, row in df_routes.iterrows():
cursor.execute("insert into table(id, version, create_ts, created_by, station_from_code, station_to_code, station_from_icao_code, station_to_icao_code) select newid() as id, 0 as version, current_timestamp as create_ts, 'source_py' as created_by, ds_dep.station_code as station_from_code, ds_arr.station_code as station_to_code, ds_dep.icao_code as station_from_icao_code, ds_arr.icao_code as station_to_icao_code from dictionary ds_dep join dictionary ds_arr on ds_dep.station_code = %s and ds_arr.station_code = %s and ds_dep.delete_ts is null and ds_arr.delete_ts is null where not exists (select null from tsp_ams_navigation_route nr where nr.station_from_code = %s and nr.station_to_code = %s and nr.delete_ts is null)",(row.station_from_code, row.station_to_code, row.station_from_code, row.station_to_code ))
conn.commit()
print('ROUTES inserted '+ row.station_from_code + '- ' + row.station_to_code)
This piece of code does not work. Execution is successful, but no rows inserted. Please assist me.
Thanks!

SAP HANA hdblci package - get data with column names

I'm using the hdbcli package to load data from SAP HANA.
Problem: When loading data, I only get the value rows without the actual headers of the SQL table.
When I load only 3 columns (as below), I can manually add them myself, even though it is very ugly. This becomes impossible when I execute a Select * statement, as I really don't want to have to add them manually and might not know when there is a change.
Question: Is there a flag / command to get the column headers from a table?
Code-MRE:
#Initialize your connection
conn = dbapi.connect(
address='00.0.000.00',
port='39015',
user='User',
password='Password',
encrypt=True,
sslValidateCertificate=False
)
cursor = conn.cursor()
sql_command = "select TITLE, FIRSTNAME, NAME from HOTEL.CUSTOMER;"
cursor.execute(sql_command)
rows = cursor.fetchall() # returns only data, not the column values
for row in rows:
for col in row:
print ("%s" % col, end=" ")
print (" ")
cursor.close()
conn.close()
Thanks to #astentx' comment I found a solution:
cursor = conn.cursor()
sql_command = "select TITLE, FIRSTNAME, NAME from HOTEL.CUSTOMER;"
cursor.execute(sql_command)
rows = cursor.fetchall() # returns only data, not the column headers
column_headers = [i[0] for i in cursor.description] # get column headers
cursor.close()
conn.close()
result = [[column_header]] # insert header
for row in rows: # insert rows
current_row = []
for cell in row:
current_row.append(cell)
result.append(current_row)

Need help using a PySimpleGUI TABLE with Sqlite3

I'm trying to delete a row from my pysimplegui table that will also delete the same row data from my sqlite3 database. Using events, I've tried to use the index eg. -TABLE- {'-TABLE-': [1]} to index the row position using values['-TABLE-'] like so:
if event == 'Delete':
row_index = 0
for num in values['-TABLE-']:
row_index = num + 1
c.execute('DELETE FROM goals WHERE item_id = ?', (row_index,))
conn.commit()
window.Element('-TABLE-').Update(values=get_table_data())
I realized that this wouldn't work since I'm using a ROW_ID in my database that Auto-increments with every new row of data and stays fixed like so (this is just to show how my database is set up):
conn = sqlite3.connect('goals.db')
c = conn.cursor()
c.execute('''CREATE TABLE goals (item_id INTEGER PRIMARY KEY, goal_name text, goal_type text)''')
conn.commit()
conn.close()
Is there a way to use the index ( values['-TABLE-'] ) to find the data inside the selected row in pysimplegui and then using the selected row's data to find the row in my sqlite3 database to delete it, or is there any other way of doing this that I'm not aware of?
////////////////////////////////////////
FIX:
Upon more reading into the docs I discovered a .get() method. This method returns a nested list of all Table Rows, the method is callable on the element of '-TABLE-'. Using values['-TABLE-'] I can also find the row index and use the .get() method to index the specific list where the Data lays which I want to delete.
Here is the edited code that made it work for me:
if event == 'Delete':
row_index = 0
for num in values['-TABLE-']:
row_index = num
# Returns nested list of all Table rows
all_table_vals = window.element('-TABLE-').get()
# Index the selected row
object_name_deletion = all_table_vals[row_index]
# [0] to Index the goal_name of my selected Row
selected_goal_name = object_name_deletion[0]
c.execute('DELETE FROM goals WHERE goal_name = ?', (selected_goal_name,))
conn.commit()
window.Element('-TABLE-').Update(values=get_table_data())
Here is a small example to delete a row from table
import sqlite3
def deleteRecord():
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
# Deleting single record now
sql_delete_query = """DELETE from SqliteDb_developers where id = 6"""
cursor.execute(sql_delete_query)
sqliteConnection.commit()
print("Record deleted successfully ")
cursor.close()
except sqlite3.Error as error:
print("Failed to delete record from sqlite table", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("the sqlite connection is closed")
deleteRecord()
In your case id will me the name of any column name which has unique value for every row in thetable of the database

How to dynamically input the table name and fetch the results in SQLite?

I have just started learning SQLite and was creating a project which has a .sqlite file in which there are multiple tables. I want to ask the user to input the table_name and then the program will fetch the columns present in that particular table.
So far I have done this.
app_database.py
def column_names(table_name):
conn = sqlite3.connect('northwind_small.sqlite')
c = conn.cursor()
c.execute("PRAGMA table_info(table_name)")
columns = c.fetchall()
for c in columns :
print(c[1])
conn.commit()
conn.close()
our-app.py
import app_database
table_name = input("Enter the table name = ")
app_database.column_names(table_name)
when I run our-app.py I don't get anything.
C:\Users\database-project>python our-app.py
Enter the table name = Employee
C:\Users\database-project>
Can anyone tell me how should I proceed?

how do i fetch sqlite column based on its len and limting 10 using python

Trying to list sqlite3 value from highest to lowest limited it to 10 using python,
here's my current code
connection = sqlite3.connect('mydb.db')
database = connection.cursor()
all_user = str(database.execute("SELECT logtext from logs order by logtext limit 10 ")
I can't figure the logic of using len(logtext)
and how to actually list from highest to lowest limiting them by 10.
Try
connection = sqlite3.connect('mydb.db')
cursor = connection.cursor()
cursor.execute("SELECT logtext from logs order by length(logtext) desc limit 10")
results = cursor.fetchall()
See also https://stackoverflow.com/a/3606923/960709

Resources