通过使用员工数据库在python中导入psycopg2。我正在尝试插入新的员工详细信息,并在员工表中显示有关员工的所有详细信息(部门编号除外),它应该显示部门名称。我不知道,任何想法都会有所帮助。 enter image description here
这是我的python代码:
import datetime
import psycopg2
conn = psycopg2.connect(database="emp", user="postgres",
password="12345", host="127.0.0.1", port="5432")
cur = conn.cursor()
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)
deptid = str(int(input("Enter department ID: ")))
salary = str(int(input("Enter your salary: ")))
cur.execute("INSERT INTO employee(emp_name, gender, hire_date,
deptid, salary) VALUES (%s, %s, %s, %s, %s)",
(emp_name, gender, hire_date, deptid, salary))
cur.execute("SELECT * FROM employee")
rows = cur.fetchall()
print('\n'.join(str(row) for row in rows))
print("Created successfully!")
conn.commit()
conn.close()
答案 0 :(得分:1)
您可以通过传递deptid
仅选择部门名称,也可以使用psycopg2.extras
cursor.execute('''SELECT deptname
from department where deptid = %(department_id)d''', {'department_id': deptid})
或者如果您想通过传递员工ID来加入
cursor.execute('''SELECT deptname
from department d join
employee e
on d.deptd = e.deptid where empno = %(employee_id)d''',
{'employee_id': empid} ) #empid from user input
import psycopg2.extras
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("""SELECT * from department""")
rows = cur.fetchall()
for row in rows:
print (" Department name : ", row['deptname']) #display department name
编辑
但是我想显示具有部门名称的员工的所有详细信息 而不是绝妙的
使用这样的查询
SELECT e.emp_no,e.emp_name,e.gender, --other columns except deptid
d.deptname
from department d join
employee e
on d.deptd = e.deptid where e.empno = ? pass the required empno