To display department ID using department name in python with psycopg2? - python

With psycopg2 in python, I'm trying to retrieve department ID using department name for new employee details by inserting as raw query. But, I couldn't able to find any solution for this problem. Is there any solution for this problem which will help me to complete my task?
This is my employee database:
This is my python code:
import datetime
import psycopg2.extras
conn = psycopg2.connect(database="emp", user="postgres",
password="12345", host="127.0.0.1",
port="5432")
cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
emp_name = str(input("Enter new employee name: "))
while True:
gender = str(input("Type your gender: "))
if gender == 'M' or gender == 'F':
break
hire_date = input("Enter hire date(YYYY-MM-DD): ")
year, month, day = map(int, hire_date.split('-'))
hiredate = datetime.date(year, month, day)
salary = str(int(input("Enter your salary: ")))
deptname = str(input("Enter department name: "))
cur.execute("INSERT INTO employee(emp_name, gender, hire_date, salary,
deptid) VALUES(%s, %s, %s, %s)",(emp_name, gender,hire_date, salary))
cur.execute("SELECT * FROM employee ORDER BY emp_no DESC LIMIT 1 WHERE
deptname = %(deptname)s", {'deptname': deptname})
rows = cur.fetchall()
print( '\n'.join( str( row ) for row in rows ) )
print( "Created successfully!" )
conn.commit()
conn.close()

To display department ID using department name can be achieved by this following query:
deptname = str(input("Enter department name: "))
cur.execute("SELECT deptid FROM department WHERE department.deptname = %("
"deptname)s", {'deptname': deptname})
deptid = cur.fetchone()

If you want only deptid, Use this.
cur.execute('''SELECT d.deptid FROM department d
WHERE d.deptname = %(deptname)s''', {'deptname': deptname})
If you want the details of all employees in that department
cur.execute('''SELECT e.* FROM employee e JOIN department d
ON d.deptid = e.deptid
WHERE d.deptname = %(deptname)s''', {'deptname': deptname})

Related

sqlite3 | data doesn't save in table

The code works when I run it but when I run it again the data from the previous run is not saved, but the table is still there. I have tried many methods of saving the file and it still doesn't save
import sqlite3
conn = sqlite3.connect('conntact.db')
cursor = conn.cursor()
check = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='contacts'");
if check == 0:
cursor.execute('''CREATE TABLE contacts
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
EMAIL TEXT NOT NULL,
PHONE TEXT NOT NULL);''');
def add_contacts():
name1 = input("Enter contact name: ")
email1 = input("Enter contact email: ")
phone1 = input("Enter contact phone number: ")
id_s = input("Enter id: ")
cursor.execute("INSERT INTO contacts (ID, NAME,EMAIL,PHONE) VALUES (?,?,?,?)", (id_s, name1, email1, phone1));
def read_all_contact():
cursor.execute("SELECT * FROM contacts");
records = cursor.fetchall()
print(f"Total rows are: {len(records)}")
for row in records:
print(f'ID: {row[0]}')
print(f'Name: {row[1]}')
print(f'Email: {row[2]}')
print(f'Phone: {row[3]}\n')
add_contacts()
read_all_contact()
conn.close()
Any help would a apreciated
Remove check = ... line, which is wrong anyway.
Remove if check == 0
Replace "CREATE TABLE contacts" with "CREATE TABLE IF NOT EXISTS contacts"
Execute conn.commit()

Python SQLite printing from a table where ID is equal set variable

This code gets the category from users input in film_list table and gets IDs of all the movies with that category:
kategorija=input("Enter the category: ")
c.execute("SELECT DISTINCT FID FROM film_list WHERE category=?", (kategorija,))
filmid = c.fetchall()
print(filmid)
I'm trying to get a name and the release year of the film with the ID that we got in a previous code fragment.
result = []
for a in filmid:
c.execute("SELECT title,release_year FROM film WHERE film_id = 'a'")
result.append(c.fetchone())
print(result)
When I enter any number, for example 1, it returns what I need, so I suppose there's something wrong in the declaration of film_id, but I don't know how I can solve this.
Full code:
import sqlite3
#Connectin to DB
conn = sqlite3.connect('sakila.db')
c = conn.cursor()
#Checking if the connection to the DB is successful
if (conn):
print("Connection successful")
else:
print ("Connection unsuccessful")
kategorija=input("Enter the category: ")
c.execute("SELECT DISTINCT FID FROM film_list WHERE category=?", (kategorija,))
filmid = c.fetchall()
print(filmid)
result = []
for a in filmid:
c.execute("SELECT title,release_year FROM film WHERE film_id = 'a'")
result.append(c.fetchone())
print(result)
You may use the following single query:
SELECT f.title, f.release_year
FROM film f
INNER JOIN film_list fl ON fl.fid = f.film_id
WHERE fl.category = ?
Your updated Python code:
sql = '''SELECT f.title, f.release_year
FROM film f
INNER JOIN film_list fl ON fl.fid = f.film_id
WHERE fl.category = ?'''
kategorija = input("Enter the category: ")
result = []
c.execute(sql, (kategorija,))
result.append(c.fetchAll())
print(result)

pymysql.err.OperationalError: (1241, 'Operand should contain 1 column(s)'). I can't determine a mistake

with connection:
with connection.cursor() as cursor:
window = Tk()
window.title('Data change')
window.geometry('500x300')
title1 = input('Name of film: ')
country1 = input('Country: ')
year1 = int(input('Year: '))
duration1 = int(input('Duration: '))
clicked2 = input('Genre: ')
clicked3 = int(input('Director ID: '))
sql = """insert into Film(director_id, title, genre, year, country, duration_in_min) values((select * from Director where Id = %s),%s, %s, %s, %s, %s);"""
var = (title1, clicked2, year1, country1, duration1, clicked3)
cursor.execute(sql, var)
connection.commit()
I can't determine what exactly the error is in this code.
You have the following subquery in the values clause:
(select * from Director where Id = %s)
This subquery likely returns more than one columns, which triggrs the error message. You should select only 1 column, or just simply use the director id directly without a subquery.
The order of your parameters do not match the order of the fields in the fieldlist of the insert. For example, the first field in the insert is director_id, but you are passing title1 parameter in the first position of your parameter array.

Python 3.6 & Inserting Values into MariaDB via variable

Code description - Running a program to add values to a maria db table. The program executes and prompts for the variables without error but the table shows no rows when I query it. Any idea where I am going wrong? Wanted to make it dynamic so I am using variables for the db and the table.
######## Output #########
[root#localhost student_program]# python db_setup.py
Connection successful!!
Database already exists: students
create_table
/usr/local/lib/python3.6/site-packages/pymysql/cursors.py:329: Warning: (1050, " Table 'students_info' already exists")
self._do_get_result()
use students;
Enter the first name :Frank
Enter the last name: Brady
Enter the email address: frank#noemail.com
Enter the address: 300 Main Street, Belfast
Enter the DOB in YYYY-MM-DD: 1980-02-02
Enter the english mark: 90
Enter the maths mark: 80
Enter the history mark: 70
Enter the science mark: 45
('INSERT into students_info (firstname, lastname,email,address,DOB,english,maths,history,science) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);', ('Frank', 'Brady', 'frank#noemail.com', '300 Main Street, Belfast', '1980-02-02', '90', '80', '70', '45'))
######### Program below #################
import os,pymysql
mariadb_root = '/var/lib/mysql/'
db_to_create = 'students'
conn = pymysql.connect(host='localhost', user='xxx', passwd='xxx', cursorclass=pymysql.cursors.DictCursor)
print('Connection successful!!')
# Check if db exists, if not create
def check_db_exists():
dbfile = os.path.join(mariadb_root, db_to_create)
if not os.path.exists(dbfile):
cur = conn.cursor()
command = "CREATE DATABASE %s;" % db_to_create
print(command)
cur.execute(command)
print("Database created %s:", db_to_create)
else:
print("Database already exists: %s" % db_to_create)
check_db_exists()
def create_database():
cur = conn.cursor()
command = "use %s; " %db_to_create
cur.execute(command)
create_table = ("""
CREATE TABLE IF NOT EXISTS students_info (
ID int NOT NULL AUTO_INCREMENT,
firstname varchar(255),
lastname varchar(255),
email varchar(255),
address varchar(255),
DOB DATE,
english varchar(255),
maths varchar(255),
history varchar(255),
science varchar(255),
PRIMARY KEY (ID));
""")
print("create_table")
cur.execute(create_table)
print(command)
create_database()
def add_student():
firstname = input("Enter the first name :")
lastname = input("Enter the last name: ")
email = input("Enter the email address: ")
address = input("Enter the address: ")
DOB = input("Enter the DOB in YYYY-MM-DD: ")
english = input("Enter the english mark: ")
maths = input("Enter the maths mark: ")
history = input("Enter the history mark: ")
science = input("Enter the science mark: ")
cur = conn.cursor()
command = "use %s; " %db_to_create
cur.execute(command)
cur.execute = ("""INSERT into students_info (firstname, lastname,email,address,DOB,english,maths,history,science) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);""",
(firstname,lastname,email,address, DOB,english,maths,history,science))
print(cur.execute)
cur.close()
conn.close()
add_student()

Use a query in sqlite value - python

Does anyone know how to execute a query inside a value in python sqlite
The eroor i am getting is:
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
my code is here:
Name = input("Enter the name of the product you want to purchase: >>")
item = Name
qty = input("Enter the Quantity of the product you want to purchase: >>")
today = date.today()
cursor = db.cursor()
cursor.execute("SELECT CatID from Products where Name=?",(Name,))
result = cursor.fetchall()
confirm = input("are you sure you want tot buy this product (y/n): >>" )
if confirm == "y":
### In this query where it says result i want to execute the data from the result query
cursor.execute("INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) Values(?,?,?,?,?)",(Username,result,today,qty,Name))
db.commit()
print("Product purchased. Thankyou for your order")
cursor.execute("UPDATE Products SET Qty = (? -1) where Name = ?",(qty,item,))
else:
print("The program will now terminate")
You can also iterate over result:
for row in result:
cursor.execute(
"INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) SELECT CatID,?,?,?,? FROM Products WHERE Name=?",(Username,row,today,qty,Name))
db.commit()

Categories