Python操作MySQL的步骤:
第一步:引入pymysql模块,连接MySQL,返回连接对象
import pymysql
conn = pymysql.Connect(
host = 'MySQL所在的主机',
port = MySQL的端口号,
user = '连接MySQL的用户名',
passwd = '连接MySQL的密码',
db = '进入的数据库名',
charset = 'utf8' # 连接编码
)
第二步:使用连接对象调用cursor()方法,返回操作数据库的对象
cursor = conn.cursor()
第三步:编写SQL
第四步:执行SQL
cursor.execute(insertSql%data)
第五步:
如果执行的是查询SQL,可以通过操作对象的fetchall()方法
获取所有符合条件的查询结果,fetchall()方法以元组的组织形式
返回所有查询结果,元组中的每一个元素是代表了每条记录的元组。
如果查询的是单条记录,则可以使用操作对象的fetchone()方法
fetchone()方法返回的是代表查询出的单条记录的元组,如果没有查到则返回None
第六步:
关闭资源
#查询所有
import pymysql
# 连接数据库,返回连接对象
conn = pymysql.Connect(
host = '10.35.165.45', # MySQL所在的主机
port = 3306, # MySQL的端口号
user = 'root', # 连接MySQL的用户名
passwd = '123456', # 连接MySQL的密码
db = 'mydb', # 进入的数据库名
charset = 'utf8' # 连接编码
)
cursor = conn.cursor() # 获取操作对象
selectSQL1 = "select name,score from student"
cursor.execute(selectSQL1) # 执行查询语句
results = cursor.fetchall() # fetchall()方法返回的是包含各个记录的元组
print("姓名 成绩")
for row in results:
print(row[0],' ',row[1])
cursor.close()
conn.close()
#查询一个
import pymysql
# 连接数据库,返回连接对象
conn = pymysql.Connect(
host = '10.35.165.45', # MySQL所在的主机
port = 3306, # MySQL的端口号
user = 'root', # 连接MySQL的用户名
passwd = '123456', # 连接MySQL的密码
db = 'mydb', # 进入的数据库名
charset = 'utf8' # 连接编码
)
cursor = conn.cursor() # 获取操作对象
selectSQL1 = "select name,score from student where stuid=%d"
cursor.execute(selectSQL1%4) # 执行查询语句
result = cursor.fetchone() # fetchone()方法返回的是代表查询出的单条记录的元组,如果没有查
#总程序
import pymysql
from 注册 import reg
while True:
choice = input("请输入你的选择 A:注册 B:登录 C:退出系统")
if choice == 'A':
reg()
elif choice == 'B':
pass
elif choice == 'C':
print('欢迎下次使用!')
break
到则返回Noneif result: print(result[0],' ',result[1])else: print("查无此人!",result)cursor.close()conn.close()
eg1 .设计一个注册、登录程序,要求用户在键盘选择
“1 注册 2 登录”,注册的信息有用户名和密码,
注册成功后使用刚才注册的用户名和密码进行登录,
登录成功后提示“欢迎xx登录本网站”,否则提示“用户名或密码不正确!”
提示:用户信息保存在数据库中的用户表中。
#总程序
import pymysql
from 注册 import reg
while True:
choice = input("请输入你的选择 A:注册 B:登录 C:退出系统")
if choice == 'A':
reg()
elif choice == 'B':
pass
elif choice == 'C':
print('欢迎下次使用!')
break
#注册系统
import pymysql
def reg():
conn = pymysql.Connect(
host='10.35.165.68',
port=3306,
user='root',
db='mywork',
passwd='123456',
charset='utf8')
s = 1
while True:
use_name = input('请输入你的注册用户名:')
use_pwd = int(input('请输入你的注册密码:'))
cursor = conn.cursor() # 获取操作对象
selectSQL = "select usename from useinfo"
cursor.execute(selectSQL) # 执行查询语句
nameinfo = cursor.fetchall()
print(nameinfo)
print('1')
for name in nameinfo:
if use_name == name[0]:
print('真可惜,您注册的用户名已经被他人抢先一步了...')
s = 0
return s
if s:
print('2')
insertSQL = "insert into useinfo(usename,usepwd)values('%s',%d)" # 编写SQL
data = (use_name,use_pwd) # SQL字符串中的占位符要填写的具体内容
cursor.execute(insertSQL%data) # 执行SQL
conn.commit()
cursor.close()
print("添加成功")
break
eg2
.设计一个“转账”程序,模拟"tom"用户给"jerry"转账200元,
一旦转账过程发生异常,则提示“系统发生异常,转账失败”,并回滚事务,
如果转账成功,则显示“转账成功”,并查看数据库验证是否真的成功。
#创建表account
create table account(
aid int auto_increment primary key,
name varchar(20) not null,
balance int not null);
#插入
insert into account(name,balance)values('tom',1000),('jerry',100);
#封装一个连接sql的函数,并返回一个conn
def getConn():
conn = pymysql.Connect(
host = '10.35.165.68',
port = 3306,
user = 'root',
passwd = '123456',
db = 'mywork',
charset = 'utf8'
)
return conn
import dbutil
conn = dbutil.getConn()
sql1 = 'update account set balance=balance-200 where aid=1'
sql2 = 'update account set balance=balance+200 where aid=2'
try:
cursor = conn.cursor()
cursor.execute(sql1)
cursor.execute(sql2)
except Exception as e:
print('系统发生故障,转账失败!故障原因:',e)
conn.rollback() # 回滚事务,为了结束事务,防止‘死锁’现象
else:
print('恭喜转账成功!')
conn.commit()