python 操作Mysql

# ### python 操作mysql

 1 # ### 1.基本语法
 2 # (1) 创建连接 host  user password database 这四个参数必须写
 3 conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db6",charset="utf8",port=3306)
 4 # (2) 创建游标对象,该对象可以进行增删改查操作
 5 cursor = conn.cursor()
 6 # (3) 执行sql语句
 7 sql = "select * from employee"
 8 # 返回的结果是查询的总条数
 9 res = cursor.execute(sql)
10 print(res)
11 # (4) 获取数据
12 res = cursor.fetchone()
13 print(res)
14 # (5) 释放游标对象
15 cursor.close()
16 # (6) 关闭数据库
17 conn.close()

# ### 2.创建/删除 数据库

 1 # 1.写一个创建表sql语句
 2 sql = """
 3 create table t1(
 4 id int unsigned primary key auto_increment,
 5 first_name char(10) not null,
 6 last_name char(10) not null,
 7 age int unsigned,
 8 sex tinyint,
 9 money float
10 )
11 """
12 # res = cursor.execute(sql)
13 # print(res)
14 
15 # 2.查看表结构
16 """
17 sql = "desc t1"
18 res = cursor.execute(sql)
19 print(res) # 返回的字段数量
20 print(cursor.fetchone())
21 """
22 
23 # 3.删除表 , 配合异常处理抑制错误,防止程序终止;
24 """
25 try:
26     sql = "drop table t1"
27     res = cursor.execute(sql)
28     print(res)
29 except:
30     pass
31 cursor.close()
32 conn.close()
33 """

python 连接mysql用到的方法与我们之前用的区别不大

python依赖器本身自带的pymysql 

首先是要实例化一个pymysql创建一个连接对象

conn = pymysql.connect(host = "用户的IP地址",user = "用户名",pwd = "密码",database = "连接的数据库名字")

e = conn .cursor()#创建一个mysql的游标对象

res = e.execute("sql语句")

print(res)#得到的是数据库返回回来的数据行数
# (4) 获取数据
res = cursor.fetchone()#得到的是真实的数据
print(res)

e.close() #关闭游标

conn.close() #关闭连接 

# 3.删除表 , 配合异常处理抑制错误,防止程序终止;

1 try:
2     sql = "drop table t1"
3     res = cursor.execute(sql)
4     print(res)
5 except:
6     pass
7 cursor.close()
8 conn.close()

# ### 3.事务处理

 1 """
 2 python 操作事务处理 只有commit提交数据,才会真正的更改数据库,否则回滚
 3 """
 4 conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db1")
 5 cursor = conn.cursor()
 6 sql1 = "begin"
 7 sql2 = "select * from t1 limit 1"
 8 sql3 = "update t1 set first_name = 'abc' where id = 4 "
 9 sql4 = "commit"
10 
11 cursor.execute(sql1)
12 cursor.execute(sql2)
13 cursor.execute(sql3)
14 cursor.execute(sql4)
15 
16 
17 cursor.close()
18 conn.close()

# ### python 操作 mysql 增删改查
import pymysql
"""
python 操作mysql 默认开启事务,必须在增删改之后,提交数据,
才会对数据库产生变化,否则默认回滚
提交数据 conn.commit()
回滚数据 conn.rollback()

execute 执行sql
executemany 执行多条sql (插入时,可以使用)
"""
# 创建连接mysql
conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db7")
# 查询数据,默认返回的是元组,可以设置参数,返回字典 pymysql.cursors.DictCursor
cursor = conn.cursor(cursor = pymysql.cursors.DictCursor)


# 增
"""
sql = "insert into t1(first_name,last_name,age,sex,money) values(%s,%s,%s,%s,%s)"
# 一次插一条数据
# res = cursor.execute(sql , ("周","永陵",81,1,9.9) )
# print(res)
# 一次插入多条数据
res = cursor.executemany(sql, [ ("马","训",20,0,15000), ("常","远",90,0,10000) , ("李","德亮",18,0,8.8) ] )
print(res)

# 获取最后一条数据的id号 (针对于单条语句的执行,获取最后id)
print(cursor.lastrowid)
# 如果是执行多条数据executemany , 通过查询的方式获取
# select id from t1 order by id desc limit 1
"""

# 删
"""
sql = "delete from t1 where id = %s"
res = cursor.execute(sql,(5,))
print(res)

if res :
print("删除成功")
else:
print("删除失败")
"""

# 改
"""
sql = "update t1 set first_name= %s where id=%s"
res = cursor.execute(sql,("王二麻子",8))
print(res)

if res:
print("更新成功")
else:
print("更新失败")
"""

# 查
sql = "select * from t1" # 6~65
res = cursor.execute(sql)
print(res)

# (1) 获取一条数据 fetchone
res = cursor.fetchone()
print(res)#{'id': 6, 'first_name': '常', 'last_name': '远', 'age': 90, 'sex': 0, 'money': 10000.0}

# (2) 获取多条数据 fetchmany 默认搜索一条,上一次查询的数据,往下获取
data = cursor.fetchmany(3)
print(data)
"""
[
{'id': 7, 'first_name': '李', 'last_name': '德亮', 'age': 18, 'sex': 0, 'money': 8.8},
{'id': 8, 'first_name': '王二麻子', 'last_name': '永陵', 'age': 81, 'sex': 1, 'money': 9.9},
{'id': 9, 'first_name': '马', 'last_name': '训', 'age': 20, 'sex': 0, 'money': 15000.0}
]
"""
for row in data:
first_name = row["first_name"]
last_name = row["last_name"]
age = row["age"]
if row["sex"] == 0:
sex = "男"
else:
sex = "女"
money = row["money"]
print("姓:{},名:{},年龄:{},性别:{},收入:{}".format(first_name,last_name,age,sex,money))

# (3) 获取所有数据 fetchall 从上一次搜索的数据,往下搜
data = cursor.fetchall()
print(data)

# 可以自定义查询的位置
print("<=================>")
sql = "select * from t1 where id >= 50"
res = cursor.execute(sql)
"""
# 1.相对滚动
# 先搜索一条 50
res = cursor.fetchone()
print(res)

# 再向后滚动3条 54
cursor.scroll(3,mode="relative")
res = cursor.fetchone()
print(res)

# 再向后滚动2条 56
cursor.scroll(2,mode="relative")
res = cursor.fetchone()
print(res)

# 在往前滚2条 error 下标越界
cursor.scroll(-30,mode="relative")
res = cursor.fetchone()
print(res)
"""
# 2.绝对滚动 相对于最开始第一条数据进行运算

1 cursor.scroll(0,mode="absolute")
2 print(cursor.fetchone())
3 cursor.scroll(3,mode="absolute")
4 print(cursor.fetchone())
5 cursor.scroll(5,mode="absolute")
6 print(cursor.fetchone())

# 在进行增删改的时候,必须替换数据,才真正进行修改,默认开启事务处理
 1 conn.commit() 2 cursor.close() 3 conn.close() 4 5  

 

 

 

 

原文地址:https://www.cnblogs.com/zyling/p/11954054.html