1. 添加一個部門。
import pymysql
def main():
no = int(input('編號: '))
name = input('名字: ')
loc = input('所在地: ')
# 1. 建立數據庫鏈接對象
con = pymysql.connect(host='localhost', port=3306,
database='hrs', charset='utf8',
user='root', password='123456')
try:
# 2. 經過鏈接對象獲取遊標
with con.cursor() as cursor:
# 3. 經過遊標執行SQL並得到執行結果
result = cursor.execute(
'insert into tb_dept values (%s, %s, %s)',
(no, name, loc)
)
if result == 1:
print('添加成功!')
# 4. 操做成功提交事務
con.commit()
finally:
# 5. 關閉鏈接釋放資源
con.close()
if __name__ == '__main__':
main()
2. 刪除一個部門。
import pymysql
def main():
no = int(input('編號: '))
con = pymysql.connect(host='localhost', port=3306,
database='hrs', charset='utf8',
user='root', password='123456',
autocommit=True)
try:
with con.cursor() as cursor:
result = cursor.execute(
'delete from tb_dept where dno=%s',
(no, )
)
if result == 1:
print('刪除成功!')
finally:
con.close()
if __name__ == '__main__':
main()
3. 更新一個部門。
import pymysql
def main():
no = int(input('編號: '))
name = input('名字: ')
loc = input('所在地: ')
con = pymysql.connect(host='localhost', port=3306,
database='hrs', charset='utf8',
user='root', password='123456',
autocommit=True)
try:
with con.cursor() as cursor:
result = cursor.execute(
'update tb_dept set dname=%s, dloc=%s where dno=%s',
(name, loc, no)
)
if result == 1:
print('更新成功!')
finally:
con.close()
if __name__ == '__main__':
main()
4. 查詢全部部門。
import pymysql
from pymysql.cursors import DictCursor
def main():
con = pymysql.connect(host='localhost', port=3306,
database='hrs', charset='utf8',
user='root', password='123456')
try:
with con.cursor(cursor=DictCursor) as cursor:
cursor.execute('select dno as no, dname as name, dloc as loc from tb_dept')
results = cursor.fetchall()
print(results)
print('編號\t名稱\t\t所在地')
for dept in results:
print(dept['no'], end='\t')
print(dept['name'], end='\t')
print(dept['loc'])
finally:
con.close()
if __name__ == '__main__':
main()
5. 分頁查詢員工信息。
import pymysql
from pymysql.cursors import DictCursor
class Emp(object):
def __init__(self, no, name, job, sal):
self.no = no
self.name = name
self.job = job
self.sal = sal
def __str__(self):
return f'\n編號:{self.no}\n姓名:{self.name}\n職位:{self.job}\n月薪:{self.sal}\n'
def main():
page = int(input('頁碼: '))
size = int(input('大小: '))
con = pymysql.connect(host='localhost', port=3306,
database='hrs', charset='utf8',
user='root', password='123456')
try:
with con.cursor() as cursor:
cursor.execute(
'select eno as no, ename as name, job, sal from tb_emp limit %s,%s',
((page - 1) * size, size)
)
for emp_tuple in cursor.fetchall():
emp = Emp(*emp_tuple)
print(emp)
finally:
con.close()
if __name__ == '__main__':
main()