使用python3 导入pymysql模块,实现是mysql数据库的基本增删改查操作。
创建好的数据库表名为sgzfy,字段分别为整数类型的dep_id,字符类型的dep_name。
pymysql的基本用法是比较简单的。无非就是sql语句得出结果。
1、单条数据插入
import pymysql
conn = pymysql.connect( ##创建与数据库的连接
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'tedu',
db = 'sgzfy',
charset = 'utf8'
)
cursor = conn.cursor() ##创建游标,可以理解为执行连接动作,把执行点放在执行位置
ins_dep = 'insert into departments values(%s, %s)' ##定义sql语句
cursor.execute(ins_dep, (1, 'tom')) ##执行sql语句
conn.commit() ##提交执行结果
cursor.close() ##关闭游标
conn.close() ##断开连接
2、多条数据插入
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'tedu',
db = 'sgzfy',
charset = 'utf8'
)
cursor = conn.cursor()
ins_dep = 'insert into departments values(%s, %s)'
values = [(2, 'jerry'),(3, 'lucy'),(4, 'lily'),(5, 'john')] ##把需要插入的数据放列表里
cursor.executemany(ins_dep, values) ##执行
conn.commit()
cursor.close()
conn.close()
3、删除dep_id为5的数据
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'tedu',
db = 'sgzfy',
charset = 'utf8'
)
cursor = conn.cursor()
del_dep = 'delete from departments where dep_id=5'
cursor.execute(del_dep)
conn.commit()
cursor.close()
conn.close()
4、修改dep_id为4的数据的dep_name为zhangsan
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'tedu',
db = 'sgzfy',
charset = 'utf8'
)
cursor = conn.cursor()
modify_dep = 'update departments set dep_name=%s where dep_id=4'
cursor.execute(modify_dep, ('zhangsan',))
conn.commit()
cursor.close()
conn.close()
5、查询数据
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'tedu',
db = 'sgzfy',
charset = 'utf8'
)
cursor = conn.cursor()
query_dep = 'select * from departments'
cursor.execute(query_dep)
r = cursor.fetchall()
print(r)
cursor.close()
conn.close()