Python学习—数据库篇之pymysql

一、pymysql简介

对于Python操作MySQL主要使用两种方式:

  • 原生模块 pymsql
  • ORM框架 SQLAchemy

pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。

二、简单使用

# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18

import pymysql

# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
#执行sql操作
r = cursor.execute("insert into student(age,sex,class_no) values(16,'male',2)")
# r为执行sql语句后受影响的行数
print(r)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

 

三、增删改查

 1 # -*- coding:utf-8 -*-
 2 # author: cdc
 3 # date: 2019/3/18
 4 
 5 import pymysql
 6 
 7 # 创建连接
 8 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
 9 # 创建游标
10 cursor = conn.cursor()
11 
12 # 增加一行数据
13 cursor.execute("insert into tb1(name,part) values('cdc',1)")
14 
15 # 字符串拼接sql(禁止使用,会引起sql注入)
16 inp_1 = ('cdcy',2,)
17 sql = "insert into tb1(name,part) values('%s','%s')" % inp_1
18 cursor.execute(sql)
19 
20 # 带参数插入数据(推荐使用)
21 inp_2 = ('cdcx',2)
22 cursor.execute("insert into tb1(name,part) values(%s,%s)",inp_2)
23 
24 
25 # 增加多行数据
26 lis = [('cdc1',2),
27        ('cdc2',2),
28        ('cdc3',2),
29        ]
30 cursor.executemany("insert into tb1(name,part) values(%s,%s)",lis)
31 
32 # 提交,不然无法保存新建或者修改的数据
33 conn.commit()
34 # 关闭游标
35 cursor.close()
36 # 关闭连接
37 conn.close()
插入数据

 1 # -*- coding:utf-8 -*-
 2 # author: cdc
 3 # date: 2019/3/18
 4 
 5 import pymysql
 6 
 7 # 创建连接
 8 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
 9 # 创建游标
10 cursor = conn.cursor()
11 #执行sql操作
12 r = cursor.execute("delete from tb1 where name=%s",('alex',))
13 # r为执行sql语句后受影响的行数
14 print(r)
15 # 提交,不然无法保存新建或者修改的数据
16 conn.commit()
17 # 关闭游标
18 cursor.close()
19 # 关闭连接
20 conn.close()
View Code

 1 # -*- coding:utf-8 -*-
 2 # author: cdc
 3 # date: 2019/3/18
 4 
 5 import pymysql
 6 
 7 # 创建连接
 8 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
 9 # 创建游标
10 cursor = conn.cursor()
11 #执行sql操作
12 r = cursor.execute("update tb1 set name=%s where part=%s",('ccc',1,))
13 # r为执行sql语句后受影响的行数
14 print(r)
15 # 提交,不然无法保存新建或者修改的数据
16 conn.commit()
17 # 关闭游标
18 cursor.close()
19 # 关闭连接
20 conn.close()
View Code

 To be continue... ...

猜你喜欢

转载自www.cnblogs.com/cdc1216/p/10549914.html