MySQL_Python开发操作MySQL
准备
安装三方库
pip install pymysql
导入三方库
import pymysql
将用户输入写入MySQL
while True:
user = input("用户名:")
passwd = input("密码:")
mobile = input("手机号:")
#连接MySQL
conn = pymysql.connect(host='',port='',user='',passwd='',charset='',db='')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#发送写入指令
sql = "insert into admin(username,password,mobile) value(%s,%s,%s)"
cursor.execute(sql, [user, pwd, mobile])
conn.commit()
#关闭
cursor.close()
conn.close()
从MySQL中删除数据
#连接MySQL
conn = pymysql.connect(host='',port='',user='',passwd='',charset='',db='')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#发送写入指令
sql = "delete from admin where id=%s;"
cursor.execute(sql, [3,])
conn.commit()
#关闭
cursor.close()
conn.close()
更新MySQL中的数据
#连接MySQL
conn = pymysql.connect(host='',port='',user='',passwd='',charset='',db='')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#发送更新指令
sql = "update admin set mobile=%s where id=%s;"
cursor.execute(sql, ["17600008888",4,])
conn.commit()
#关闭
cursor.close()
conn.close()
查询MySQL中的数据
#连接MySQL
conn = pymysql.connect(host='',port='',user='',passwd='',charset='',db='')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#发送查询指令
sql = "select * from admin where id>2;"
cursor.execute(sql)
data_list = cursor.fetchall() #fetchone() 只获取符合条件の一条数据
for row_dict in data_list:
print(row_dict)
#关闭
cursor.close()
conn.close()