- 交互类型
安装pymysql模块
1、python3
模块名:pymysql
安装:
在线:sudo pip3 install pymysql
#pip用来安装模块,apt-get用来安装app
离线:pymysql-0.7.11.tar.gz
$tar -zxvf pymysql-0.7.11.tar.gz
$cd pymysql-0.7.11
$sudo python3 setup.py [install]
2、python2
模块名:MySQLdb
安装:sudo pip install mysql-python
3、示例:
#python与mysql交互
import pymysql
#1.创建与数据库连接对象
db1 = pymysql.connect(host = "localhost",user="root",
password = "7952852741",database = "db1",
charset="utf8")
#2.利用db方法创建游标对象
cur = db1.cursor() #创建游标对象
#3.利用游标对象的execute()方法执行SQL命令
cur.execute('insert into sheng values(16,300000,"台湾省");')
#4.提交到数据库执行
db1.commit()
#5.关闭游标对象
cur.close()
#6.断开数据库连接
db1.close()
安装sqlalchemy库
在线:sudo pip3 install sqlalchemy
离线:tar -xzvf SQLAlchemy-1.2.10.tar.gz
cd SQLAlchemy-1.2.10
sudo python3 setup.py install
验证:python中 import sqlalchemy
- pymysql使用流程
1、建立数据库连接(db = pymysql.connect(...))
2、创建游标对象(c = db.cursor())
3、游标方法 c.execute("insert ....") #sql命令
4、提交到数据库:db.commit()
5、关闭游标对象:c.close()
6、断开数据库连接:db.close()
- 数据库操作的对象方法
1、db = pymysql.connect(参数列表)
1、host:主机地址,本地 localhost
2、port:端口号,默认3306
3、user:用户名
4、password:密码
5、database:库
6、charset:编码方式,推荐使用 utf8
2、数据库连接对象(db)的方法
1、db.close() 关闭连接
2、db.commit() 提交到数据库执行
3、db.rollback() 回滚
4、c =db.cursor() 返回游标对象,用于执行具体SQL命令
3、游标对象(cur)的方法
1、cur.execute(SQL命令) 执行SQL命令
2、cur.close() 关闭游标对象
3、cur.fetchone() 获取查询结果集的第一条数据
4、cur.fetchmany(n) 获取n条
((记录1),(记录2),(记录3)...)#以元组形式返回
4、cur.fetchall() 获取所有记录
示例:cur.fetch…函数
#此示例演示 cur.fetchone cur.fetchmany方法的使用
import pymysql
try:
db = pymysql.connect(host = 'localhost',user='root',\
password = '7952852741',database = 'db1',charset='utf8')
cur = db.cursor()
sql_select = "select * from sheng;"
cur.execute(sql_select)
data1 = cur.fetchone()
print(data1)
data2 = cur.fetchmany(3)
print(data2)
#for m in data2:
# print(m) 可以遍历每个大元组里的小元组
data3 = cur.fetchall()
print(data3)
cb.commit()
except Exception as e:
print(e);
cur.close()
db.close()
- 参数化操作(防止sql注入攻击)
cur.execute(sql语句,[参数列表])
import
db = pymysql.connect(host = 'localhost',user='root',\
password = '7952852741',database = 'db1',charset='utf8')
cur = db.cursor()
s_id = input("请输入省编号")
s_name = input("请输入省名称")
try:
sql_insert = "insert into sheng values(%s,%s);"
cur.execute(sql_insert,[s_id,name])
print("succeed")
db.commit()
except Exception as e:
db.rollback() #错误即事务回滚
print("failed",e)
cur.close()
db.close()
- python与mysql交互重复代码的封装
#此代码用来封装mysql的重用代码
from pymysql import *
class mysqlpython:
def __init__(self,database,
host='localhost',
user = "root",
password=123456789',
port = 3306,
charset='utf8'):
'''传入默认参数'''
self.user = user
self.host = host
self.password = password
self.port = port
self.charset = charset
self.database = database
def open(self):
'''连接数据库并打开游标'''
self.db = connect(host = self.host,
user = self.user,
port = self.port,
password=self.password,
database = self.database,
charset = self.charset)
self.cur = self.db.cursor()
def sql_do(self,sql,L=[]):
'''执行sql语句'''
try:
if L == []:
self.cur.execute(sql)
else:
self.cur.execute(sql,L)
self.db.commit()
except Exception as e:
print('failed',e)
self.close()
def all(self,sql,L=[]):
'''查看表信息'''
try:
self.open()
self.cur.execute(sql,L)
result = self.cur.fetchall()
self.db.commit()
return result
except Exception as e:
self.db.rollback()
print('Failed',e)
self.close()
def close(self):
'''关闭数据库连接'''
self.cur.close()
self.db.close()
- 业务方面:交互数据的加密
#采用sha1算法对用户账号密码的加密
from hashlib import sha1
from mysqlpython import *
uname = print("请输入用户账号:")
pwd = print("请输入用户密码:")
s1 = sha1() #建立sha1对象
s1.update(pwd.encode("utf8")) #对pwd进行sha1加密
pwd2 = s1.hexdigest() #对加密后的结果转换为16进制
sql_select = "select password from user where uname = %s;"
db1 = mysqlpython("db1")
result = db1.all(sql_select,[uname]) #返回数据的大元组
if len(result) == 0:
print("账号不存在!")
elif result[0][0] != pwd2:
print("密码错误!")
else:
print("登录成功!")