microsoft office2003免费版下载-蓝牙适配器驱动

cf更新失败
2023年3月30日发(作者:windows7壁纸)

Python连接MySQL数据库

⼀、连接数据库

1、下载安装pymyql库

pipinstallpymysql

2、导⼊库

importpymysql

3、连接数据库,最好⽤tryexcept捕获异常

try:

db=t(host="localhost",user="root",password="****",database="test")

print('数据库连接成功!')

se:

print('数据库连接失败'+str(e))

⼆、创建⼀张新表

1、声明⼀个游标

cur=()

2、创建表之前先检查是否存在,如果存在则删除

e('DROPTABLEIFEXISTSStudent')

3、编辑sql语句

sqlQuery="CREATETABLEStudent(NameCHAR(20)NOTNULL,EmailCHAR(20),Ageint)"

e(sqlQuery)

三、向表中插⼊⼀条数据

1、编辑sql语句

sqlQuery="INSERTINTOStudent(Name,Email,Age)VALUE(%s,%s,%s)"

2、编辑准备插⼊的值

value=('Mike','123456@',20)

3、执⾏sql语句

try:

e(sqlQuery,value)

()

print('数据插⼊成功!')

se:

print("数据插⼊失败:"+e)

ck()

四、查询表中的数据

1、编辑sql语句

sqlQuery="SELECT*FROMStudent"

2、使⽤fetchall()⽅法接收全部的返回结果⾏

try:

e(sqlQuery)

results=ll()

forrowinresults:

name=row[0]

email=row[1]

age=row[2]

print('Name:%s,Email:%s,Age:%s'%(name,email,age))

se:

print("数据查询失败:"+str(e))

五、更新表中的数据

1、编辑sql语句

sqlQuery="UPDATEStudentSETName=%sWHEREName=%s"

2、编辑更新的信息

value=('John','updatedname')

3、提交修改

try:

e(sqlQuery,value)

()

print('数据更新成功!')

se:

print("数据更新失败:"+str(e))

#发⽣错误时回滚

ck()

六、删除表中的数据

1、编辑sql语句

sqlQuery="DELETEFROMStudentwhereName=%s"

2、编辑更新的信息

value=('John')

3、提交修改

try:

e(sqlQuery,value)

()

print('DateDeletedSuccessfully')

se:

print("数据删除失败:"+str(e))

#发⽣错误时回滚

ck()

七、删除⼀张表

1、编辑sql语句

sqlQuery='DROPTABLEIFEXISTSStudent'

2、提交修改

e(sqlQuery)

print('表删除成功!')

完整demo:

importpymysql

#/qq_39598271/article/details/112610382

#Python3.8问题

try:

db=t(host="localhost",user="root",password="*****",database="test")

print('数据库连接成功!')

#创建⼀张表

cur=()

#e('DROPTABLEIFEXISTSStudent')

#sqlQuery="CREATETABLEStudent(NameCHAR(20)NOTNULL,EmailCHAR(20),Ageint)"

#e(sqlQuery)

#向表中插⼊数据

#cur=()

#sqlQuery="INSERTINTOStudent(Name,Email,Age)VALUE(%s,%s,%s)"

#value=('Mike','123456@',20)

#try:

#e(sqlQuery,value)

#()

#print('数据插⼊成功!')

#se:

#print("数据插⼊失败:"+e)

#ck()

#查询表中数据

#cur=()

#sqlQuery="SELECT*FROMStudent"

#try:

#e(sqlQuery)

#results=ll()

#forrowinresults:

#name=row[0]

#email=row[1]

#age=row[2]

#print('Name:%s,Email:%s,Age:%s'%(name,email,age))

#se:

#print("数据查询失败:"+str(e))

#更新表中数据

#cur=()

#sqlQuery="UPDATEStudentSETName=%sWHEREName=%s"

#value=('John','updatedname')

#try:

#e(sqlQuery,value)

#()

#print('数据更新成功!')

#se:

#print("数据更新失败:"+str(e))

##发⽣错误时回滚

#ck()

#删除表中数据

#cur=()

#sqlQuery="DELETEFROMStudentwhereName=%s"

#value=('John')

#try:

#e(sqlQuery,value)

#()

#print('DateDeletedSuccessfully')

#se:

#print("数据删除失败:"+str(e))

##发⽣错误时回滚

#ck()

#删除⼀张表

cur=()

sqlQuery='DROPTABLEIFEXISTSStudent'

e(sqlQuery)

print('表删除成功!')

se:

print('数据库连接失败'+str(e))

更多推荐

cf更新失败