python数据库编程 Mysql实现通讯录
本文实例为大家分享了Mysql实现通讯录的具体代码,供大家参考,具体内容如下
#-*-code:utf-8-*-
importpymysql
defCreateTable():
hcon=pymysql.connect(host='localhost',user='root',password='lptpwd',database='contract',charset='utf8')
hcur=hcon.cursor()
hcur.execute('droptableifexistscontractlist')
ctable='''
createtablecontractlist
(
IDint(10)primarykey,
NAMEvarchar(20)notnull,
TELFchar(11)notnull,
TELSchar(11),
OTHERvarchar(50)
)engine=myisamcharset=utf8;
'''
hcur.execute(ctable)
hcur.close()
hcon.close()
defAddInfo(hcon,hcur):
id=int(input('pleaseinputID:'))
name=str(input('pleaseinputName:'))
telf=str(input('pleaseinputTel1:'))
tels=str(input('pleaseinputTel2:'))
other=str(input('pleaseinputother:'))
sql="insertintocontractlist(id,name,telf,tels,other)values(%s,%s,%s,%s,%s)"
try:
hcur.execute(sql,(id,name,telf,tels,other))
hcon.commit()
except:
hcon.rollback()
defDeleteInfo(hcon,hcur):
SelectInfo(hcon,hcur)
did=int(input('pleaseinputidofdelete:'))
sql="deletefromcontractlistwhereid=%s"
try:
hcur.execute(sql,(did,))
hcon.commit()
except:
hcon.rollback()
defUpdateInfo(hcon,hcur):
SelectInfo(hcon,hcur)
did=int(input('pleaseinputidofupdate:'))
sqlname="updatecontractlistsetname=%swhereid=%s"
name=str(input('pleaseinputName:'))
try:
hcur.execute(sqlname,(name,did))
hcon.commit()
except:
hcon.rollback()
sqltelf="updatecontractlistsettelf=%swhereid=%s"
telf=str(input('pleaseinputTel1:'))
try:
hcur.execute(sqltelf,(telf,did))
hcon.commit()
except:
hcon.rollback()
sqltels="updatecontractlistsettels=%swhereid=%s"
tels=str(input('pleaseinputTel2:'))
try:
hcur.execute(sqltels,(tels,did))
hcon.commit()
except:
hcon.rollback()
sqlothers="updatecontractlistsetother=%swhereid=%s"
other=str(input('pleaseinputother:'))
try:
hcur.execute(sqlothers,(other,did))
hcon.commit()
except:
hcon.rollback()
defSelectInfo(hcon,hcur):
hcur.execute("select*fromcontractlist")
result=hcur.fetchall()
ptitle=('ID','Name','Tel1','Tel2','Other')
print(ptitle)
forfindexinresult:
print(findex)
print('')
defMeau():
print('1.diaplay')
print('2.add')
print('3.update')
print('4.delete')
print('5.cls')
print('0.exit')
sel=9
while(sel>5orsel<0):
sel=int(input('pleasechoice:'))
returnsel
defmain():
#CreateTable()
hcon=pymysql.connect(host='localhost',user='root',password='ltb12315',database='contract',charset='utf8')
hcur=hcon.cursor()
while(True):
sel=Meau()
if(sel==1):
SelectInfo(hcon,hcur)
elif(sel==2):
AddInfo(hcon,hcur)
elif(sel==3):
UpdateInfo(hcon,hcur)
elif(sel==4):
DeleteInfo(hcon,hcur)
elif(sel==5):
os.system('cls')
else:
break
print('-------------------------')
hcur.close()
hcon.close()
if__name__=="__main__":
main()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。