一、數據庫基礎用法
要先配置環境變量,然后cmd安裝:pip install pymysql
1、連接MySQL,並創建wzg庫
#引入decimal模塊
import pymysql
#連接數據庫
db=pymysql.connect(host='localhost',user='root',password='1234',charset='utf8')
#創建一個游標對象(相當於指針)
cursor=db.cursor()
#執行創建數據庫語句
cursor.execute('create schema wzg default charset=utf8;')
cursor.execute('show databases;')
#fetchone獲取一條數據(元組類型)
print(cursor.fetchone())
#現在指針到了[1]的位置
#fetchall獲取全部數據(字符串類型)
all=cursor.fetchall()
for i in all:
print(i[0])
#關閉游標和數據庫連接
cursor.close()
db.close()
2、創建student表,並插入數據
import pymysql
#連接數據庫,並打開wzg數據庫(數據庫已創建)
db=pymysql.connect(host='localhost',user='root',password='1234',charset='utf8',db='wzg')
#創建游標對象
cursor=db.cursor()
try:
#創建student表,並執行
sql='''create table student(
SNO char(10),
SNAME varchar(20) NOT NULL,
SSEX varchar(1),
primary key(SNO)
)default charset=utf8;'''
cursor.execute(sql)
#插入一條數據,並執行
insert_sql='''
insert into student values('200303016','王智剛','男'),('20030001','小明','男')
'''
cursor.execute(insert_sql)
#將數據提交給數據庫(加入數據,修改數據要先提交)
db.commit()
#執行查詢語句
cursor.execute('select * from student')
#打印全部數據
all=cursor.fetchall()
for i in all:
print(i)
#發生錯誤時,打印報錯原因
except Exception as e:
print(e)
#無論是否報錯都執行
finally:
cursor.close()
db.close()
數據庫中char和varchar的區別:
char類型的長度是固定的,varchar的長度是可變的。
例如:存儲字符串'abc',使用char(10),表示存儲的字符將占10個字節(包括7個空字符),
使用varchar(10),表示只占3個字節,10是最大值,當存儲的字符小於10時,按照實際的長度存儲。
二、項目:銀行管理系統
完成功能:1.查詢 2.取錢 3.存錢 4.退出
練習:創建信息表,並進行匹配
1、創建數據庫為(bank),賬戶信息表為(account)
account_id(varchar(20)) | Account_passwd(char(6)) | Money(decimal(10,2)) |
---|---|---|
001 | 123456 | 1000.00 |
002 | 456789 | 5000.00 |
2、拓展:進行賬號和密碼的匹配
請輸入賬號:001
請輸入密碼:123456
select * from account where account_id=001 and Account_passwd=123456
if cursor.fetchall():
登錄成功
else:
登錄失敗
import pymysql
# 連接數據庫
db = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8')
cursor = db.cursor()
# 創建bank庫
cursor.execute('create database bank charset utf8;')
cursor.execute('use bank;')
try:
# # 創建表
# sql = '''create table account(
# account_id varchar(20) NOT NULL,
# account_passwd char(6) NOT NULL,
# money decimal(10,2),
# primary key(account_id)
# );'''
# cursor.execute(sql)
# # 插入數據
# insert_sql = '''
# insert into account values('001','123456',1000.00),('002','456789',5000.00)
# '''
# cursor.execute(insert_sql)
# db.commit()
# # 查詢所有數據
# cursor.execute('select * from account')
# all = cursor.fetchall()
# for i in all:
# print(i)
# 輸入賬號和密碼
z=input("請輸入賬號:")
m=input("請輸入密碼:")
# 從account表中進行賬號和密碼的匹配
cursor.execute('select * from account where account_id=%s and account_passwd=%s',(z,m))
# 如果找到,則登錄成功
if cursor.fetchall():
print('登錄成功')
else:
print('登錄失敗')
except Exception as e:
print(e)
finally:
cursor.close()
db.close()
1、進行初始化操作
import pymysql
# 創建bank庫
CREATE_SCHEMA_SQL='''
create schema bank charset utf8;
'''
# 創建account表
CREATE_TABLE_SQL = '''
create table account(
account_id varchar(20) NOT NULL,
account_passwd char(6) NOT NULL,
# decimal用於保存精確數字的類型,decimal(10,2)表示總位數最大為12位,其中整數10位,小數2位
money decimal(10,2),
primary key(account_id)
) default charset=utf8;
'''
# 創建銀行賬戶
CREATE_ACCOUNT_SQL = '''
insert into account values('001','123456',1000.00),('002','456789',5000.00);
'''
# 初始化
def init():
try:
DB = pymysql.connect(host='localhost',user='root',password='1234',charset='utf8')
cursor1 = DB.cursor()
cursor1.execute(CREATE_SCHEMA_SQL)
DB = pymysql.connect(host='localhost',user='root',password='1234',charset='utf8',database='bank')
cursor2 = DB.cursor()
cursor2.execute(CREATE_TABLE_SQL)
cursor2.execute(CREATE_ACCOUNT_SQL)
DB.commit()
print('初始化成功')
except Exception as e:
print('初始化失敗',e)
finally:
cursor1.close()
cursor2.close()
DB.close()
# 不讓別人調用
if __name__ == "__main__":
init()
2、登錄檢查,並選擇操作
import pymysql
# 定義全局變量為空
DB=None
# 創建Account類
class Account():
# 傳入參數
def __init__(self,account_id,account_passwd):
self.account_id=account_id
self.account_passwd=account_passwd
# 登錄檢查
def check_account(self):
cursor=DB.cursor()
try:
# 把輸入賬號和密碼進行匹配(函數體內部傳入參數用self.)
SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)
cursor.execute(SQL)
# 匹配成功返回True,失敗返回False
if cursor.fetchall():
return True
else:
return False
except Exception as e:
print("錯誤原因:",e)
finally:
cursor.close()
# 查詢余額
# def query_money
# 取錢
# def reduce_money
# 存錢
# def add_money
def main():
# 定義全局變量
global DB
# 連接bank庫
DB=pymysql.connect(host="localhost",user="root",passwd="1234",database="bank")
cursor=DB.cursor()
# 輸入賬號和密碼
from_account_id=input("請輸入賬號:")
from_account_passwd=input("請輸入密碼:")
# 輸入的參數傳入給Account類,並創建account對象
account=Account(from_account_id,from_account_passwd)
# 調用check_account方法,進行登錄檢查
if account.check_account():
choose=input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
# 當輸入不等於4的時候執行,等於4則退出
while choose!="4":
# 查詢
if choose=="1":
print("111")
# 取錢
elif choose=="2":
print("222")
# 存錢
elif choose=="3":
print("333")
# 上面操作完成之后,繼續輸入其他操作
choose = input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
else:
print("謝謝使用!")
else:
print("賬號或密碼錯誤")
DB.close()
main()
3、加入查詢功能
存在銀行里的錢可能會產生利息,所以需要考慮余額為小數的問題,需要用到decimal庫
import pymysql
# 引入decimal模塊
import decimal
DB=None
class Account():
def __init__(self,account_id,account_passwd):
self.account_id=account_id
self.account_passwd=account_passwd
# 登錄檢查
def check_account(self):
cursor=DB.cursor()
try:
SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)
cursor.execute(SQL)
if cursor.fetchall():
return True
else:
return False
except Exception as e:
print("錯誤",e)
finally:
cursor.close()
# 查詢余額
def query_money(self):
cursor=DB.cursor()
try:
# 匹配賬號密碼,並返回money
SQL="select money from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)
cursor.execute(SQL)
money=cursor.fetchone()[0]
# 如果賬戶有錢就返回金額,沒錢返回0.00
if money:
# 返回值為decimal類型,quantize函數進行四舍五入,'0.00'表示保留兩位小數
return str(money.quantize(decimal.Decimal('0.00')))
else:
return 0.00
except Exception as e:
print("錯誤原因",e)
finally:
cursor.close()
def main():
global DB
DB=pymysql.connect(host="localhost",user="root",passwd="1234",charset="utf8",database="bank")
cursor=DB.cursor()
from_account_id=input("請輸入賬號:")
from_account_passwd=input("請輸入密碼:")
account=Account(from_account_id,from_account_passwd)
if account.check_account():
choose=input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
while choose!="4":
# 查詢
if choose=="1":
# 調用query_money方法
print("您的余額是%s元" % account.query_money())
# 取錢
elif choose=="2":
print("222")
# 存錢
elif choose=="3":
print("333")
choose = input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
else:
print("謝謝使用")
else:
print("賬號或密碼錯誤")
DB.close()
main()
4、加入取錢功能
取錢存錢要用update來執行數據庫,還要注意取錢需要考慮余額是否充足的問題
import pymysql
import decimal
DB=None
class Account():
def __init__(self,account_id,account_passwd):
self.account_id=account_id
self.account_passwd=account_passwd
# 登錄檢查
def check_account(self):
cursor=DB.cursor()
try:
SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)
cursor.execute(SQL)
if cursor.fetchall():
return True
else:
return False
except Exception as e:
print("錯誤",e)
finally:
cursor.close()
# 查詢余額
def query_money(self):
cursor=DB.cursor()
try:
SQL="select money from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)
cursor.execute(SQL)
money=cursor.fetchone()[0]
if money:
return str(money.quantize(decimal.Decimal('0.00')))
else:
return 0.00
except Exception as e:
print("錯誤原因",e)
finally:
cursor.close()
# 取錢(注意傳入money參數)
def reduce_money(self,money):
cursor = DB.cursor()
try:
# 先調用query_money方法,查詢余額
has_money=self.query_money()
# 所取金額小於余額則執行(注意類型轉換)
if decimal.Decimal(money) <= decimal.Decimal(has_money):
# 進行數據更新操作
SQL="update account set money=money-%s where account_id=%s and account_passwd=%s" %(money,self.account_id,self.account_passwd)
cursor.execute(SQL)
# rowcount進行行計數,行數為1則將數據提交給數據庫
if cursor.rowcount==1:
DB.commit()
return True
else:
# rollback數據庫回滾,行數不為1則不執行
DB.rollback()
return False
else:
print("余額不足")
except Exception as e:
print("錯誤原因",e)
finally:
cursor.close()
# 存錢
# def add_money
def main():
global DB
DB=pymysql.connect(host="localhost",user="root",passwd="1234",charset="utf8",database="bank")
cursor=DB.cursor()
from_account_id=input("請輸入賬號:")
from_account_passwd=input("請輸入密碼:")
account=Account(from_account_id,from_account_passwd)
if account.check_account():
choose=input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
while choose!="4":
# 查詢
if choose=="1":
print("您的余額是%s元" % account.query_money())
# 取錢
elif choose=="2":
# 先查詢余額,再輸入取款金額,防止取款金額大於余額
money=input("您的余額是%s元,請輸入取款金額" % account.query_money())
# 調用reduce_money方法,money不為空則取款成功
if account.reduce_money(money):
print("取款成功,您的余額還有%s元" % account.query_money())
else:
print("取款失敗!")
# 存錢
elif choose=="3":
print("333")
choose = input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
else:
print("謝謝使用!")
else:
print("賬號或密碼錯誤")
DB.close()
main()
5、加入存錢功能
存錢功能和取錢功能相似,而且不需要考慮余額的問題,至此已完善當前所有功能
import pymysql
import decimal
DB=None
class Account():
def __init__(self,account_id,account_passwd):
self.account_id=account_id
self.account_passwd=account_passwd
# 登錄檢查
def check_account(self):
cursor=DB.cursor()
try:
SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)
cursor.execute(SQL)
if cursor.fetchall():
return True
else:
return False
except Exception as e:
print("錯誤",e)
finally:
cursor.close()
# 查詢余額
def query_money(self):
cursor=DB.cursor()
try:
SQL="select money from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)
cursor.execute(SQL)
money=cursor.fetchone()[0]
if money:
return str(money.quantize(decimal.Decimal('0.00')))
else:
return 0.00
except Exception as e:
print("錯誤原因",e)
finally:
cursor.close()
# 取錢
def reduce_money(self,money):
cursor = DB.cursor()
try:
has_money=self.query_money()
if decimal.Decimal(money) <= decimal.Decimal(has_money):
SQL="update account set money=money-%s where account_id=%s and account_passwd=%s" %(money,self.account_id,self.account_passwd)
cursor.execute(SQL)
if cursor.rowcount==1:
DB.commit()
return True
else:
DB.rollback()
return False
else:
print("余額不足")
except Exception as e:
print("錯誤原因",e)
finally:
cursor.close()
# 存錢
def add_money(self,money):
cursor = DB.cursor()
try:
SQL="update account set money=money+%s where account_id=%s and account_passwd=%s" %(money,self.account_id,self.account_passwd)
cursor.execute(SQL)
if cursor.rowcount==1:
DB.commit()
return True
else:
DB.rollback()
return False
except Exception as e:
DB.rollback()
print("錯誤原因",e)
finally:
cursor.close()
def main():
global DB
DB=pymysql.connect(host="localhost",user="root",passwd="1234",charset="utf8",database="bank")
cursor=DB.cursor()
from_account_id=input("請輸入賬號:")
from_account_passwd=input("請輸入密碼:")
account=Account(from_account_id,from_account_passwd)
if account.check_account():
choose=input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
while choose!="4":
# 查詢
if choose=="1":
print("您的余額是%s元" % account.query_money())
# 取錢
elif choose=="2":
money=input("您的余額是%s元,請輸入取款金額" % account.query_money())
if account.reduce_money(money):
print("取款成功,您的余額還有%s元" % account.query_money())
else:
print("取款失敗!")
# 存錢
elif choose=="3":
money=input("請輸入存款金額:")
if account.add_money(money):
print("存款成功,您的余額還有%s元,按任意鍵繼續\n" % (account.query_money()))
else:
print("存款失敗,按任意鍵繼續")
choose = input("請輸入操作:\n1、查詢余額\n2、取錢\n3、存錢\n4、取卡\n")
else:
print("謝謝使用!")
else:
print("賬號或密碼錯誤")
DB.close()
main()
三、拓展-學生信息管理系統
創建student表:
('2016081111','張三','20','男','軟件工程學院','2016','3'),
('2016061111','王傑','21','男','網絡工程學院','2016','3'),
('2016071113','周順','19','男','大氣科學學院','2016','3'),
('2017081180','李偉','20','男','軟件工程學院','2017','2'),
('2016081201','王麗','20','女','軟件工程學院','2016','5')
實現功能:
1、查詢所有學生的信息
2、按學號查詢學生的信息
3、添加學生信息
4、修改學生信息
5、刪除學生信息
6、退出
1、初始化
import pymysql
# 創建wzg庫
CREATE_SCHEMA_SQL = '''
create schema wzg charset utf8;
'''
# 創建student表
CREATE_TABLE_SQL = '''create table student(
sno varchar(10) primary key,
sname varchar(10),
sage varchar(3),
ssex enum('男', '女'),
sadcademy varchar(20),
sgrade varchar(4),
sclass varchar(2)
)default charset=utf8
'''
# 插入數據
CREATE_student_SQL = '''
insert into student values('2016081111','張三','20','男','軟件工程學院','2016','3'),
('2016061111','王傑','21','男','網絡工程學院','2016','3'),
('2016071113','周順','19','男','大氣科學學院','2016','3'),
('2017081180','李偉','20','男','軟件工程學院','2017','2'),
('2016081201','王麗','20','女','軟件工程學院','2016','5')
'''
# 初始化
def init():
try:
DB = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8')
cursor1 = DB.cursor()
cursor1.execute(CREATE_SCHEMA_SQL)
DB = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8', database='wzg')
cursor2 = DB.cursor()
cursor2.execute(CREATE_TABLE_SQL)
cursor2.execute(CREATE_student_SQL)
DB.commit()
print('初始化成功')
except Exception as e:
print('初始化失敗', e)
finally:
cursor1.close()
cursor2.close()
DB.close()
# 不讓別人調用
if __name__ == "__main__":
init()
2、主函數
import pymysql
class Student():
#查詢所有學生信息
def all_student(self):
cursor = DB.cursor()
cursor.execute('select * from student;')
for i in cursor.fetchall():
print(i)
#按學號查詢學生信息
def sno_student(self):
cursor = DB.cursor()
sno=input("請輸入學號:")
cursor.execute('select * from student where sno=%s;' % sno)
a=cursor.fetchone()
if a:
print(a)
else:
print('該學號不存在')
#添加學生信息
def add_student(self):
cursor = DB.cursor()
a1 = input("請輸入學號:")
a2 = input("請輸入姓名:")
a3 = input("請輸入年齡:")
a4 = input("請輸入性別:")
a5 = input("請輸入院系:")
a6 = input("請輸入:入學年份")
a7 = input("請輸入班級:")
cursor.execute('select * from student;')
for i in cursor.fetchall():
if a1==i[0]:
print('學號已存在')
break
else:
sql='insert into student values("%s","%s","%s","%s","%s","%s","%s");' % (a1,a2,a3,a4,a5,a6,a7)
cursor.execute(sql)
DB.commit() #提交數據
print('添加成功')
#修改學生信息
def set_student(self):
cursor = DB.cursor()
sno=input('請輸入要修改的學號:')
cursor.execute('select * from student;')
for i in cursor.fetchall():
if sno == i[0]:
a = input('輸入要修改的字段:\nsno,sname,sage,ssex,sadcademy,sgrade,sclass\n')
b = input('修改為:')
SQL = 'update student set %s="%s" where sno="%s";' % (a,b,sno)
cursor.execute(SQL)
if cursor.rowcount == 1: #行計數
DB.commit()
print('修改成功')
else:
DB.rollback() #數據庫回滾
print('修改失敗')
break
else:
print('學號不存在')
#刪除學生信息
def del_student(self):
cursor = DB.cursor()
sno = input("請輸入學號:")
cursor.execute('delete FROM student WHERE sno=%s;' % sno)
if cursor.rowcount==1:
DB.cursor()
print('刪除成功')
else:
DB.rollback()
print('該學號不存在')
def main():
global DB
student = Student()
DB = pymysql.connect(host="localhost", user="root", password="1234", database="wzg")
cursor = DB.cursor()
choose = input("*************\n請選擇您的操作:\n1、查詢所有學生的信息\n2、按學號查詢學生的信息\n3、添加學生信息\n4、修改學生信息\n5、刪除學生信息\n6、退出\n")
while choose != "6":
if choose=="1":
student.all_student()
elif choose=="2":
student.sno_student()
elif choose == "3":
student.add_student()
elif choose == "4":
student.set_student()
elif choose == "5":
student.del_student()
choose = input("*************\n請選擇您的操作:\n1、查詢所有學生的信息\n2、按學號查詢學生的信息\n3、添加學生信息\n4、修改學生信息\n5、刪除學生信息\n6、退出\n")
else:
print('已退出!')
DB.close()
main()
聲明:未經許可,不得轉載