python 最好用的数据库模块_Python 使用pymysql模块操作数据库

Python 中操作 MySQL 步骤

看完了上面的这个操作流程,那么python操作数据库可以用上面模块来操作呢?

目前比较流行的就是pymysql,下面来看看介绍。

pymysql介绍PyMySQL是一个纯Python写的MySQL客户端,它的目标是替代MySQLdb,可以在CPython、PyPy、IronPython和Jython环境下运行。PyMySQL在MIT许可下发布。

PyMySQL的性能和MySQLdb几乎相当,如果对性能要求

不是特别的强,使用PyMySQL将更加方便。

PyMySQL的使用方法和MySQLdb几乎一样。

下面再来一番系统概念,进入引申后面web开发框架需要用到的数据以及知识。

引入模块

在py文件中引入pymysql模块from pymysql import *

Connection 对象

conn=connect(参数列表)

用于建立与数据库的连接

创建对象:调用connect()方法

参数列表:参数host:连接的mysql主机,如果本机是'localhost'

参数port:连接的mysql主机的端口,默认是3306

参数database:数据库的名称

参数user:连接的用户名

参数password:连接的密码

参数charset:通信采用的编码方式,推荐使用utf8

对象的方法close()关闭连接

commit()提交

cursor()返回Cursor对象,用于执行sql语句并获得结果

execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行- -

insert、update、delete语句,也可以执行create、alter、drop等语句

fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组

fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回

Cursor对象用于执行sql语句,使用频度最高的语句为select、insert、update、delete

获取Cursor对象:调用Connection对象的cursor()方法

cs1=conn.cursor()

对象的属性rowcount只读属性,表示最近一次execute()执行后受影响的行数

connection获得当前连接对象

安装PyMysql

pip install pymysql

好了,安装好了pymysql模块之后,首先需要创建mysql的相关数据,方便后续使用。

Mysql创建数据库test_dbCREATE DATABASE IF NOT EXISTS test_db CHARACTER SET utf8 COLLATE utf8_general_ci;

Mysql创建表 - 胖子们的爱好表fatboy_hobbycreate table fatboy_hobby(

id int unsigned primary key auto_increment not null,

name varchar(40) default null COMMENT "肥仔名称",

hobby varchar(40) default null COMMENT "肥仔爱好",

professional varchar(40) default null COMMENT "肥仔职业",

address varchar(40) default null COMMENT "肥仔居住地"

);

Mysql插入数据insert into fatboy_hobby VALUES(null,"胖子老板","斗地主","小卖铺老板","西九龙");

insert into fatboy_hobby VALUES(null,"肥仔白","打dota、吃槟榔","挨踢攻城狮","铜锣湾");

insert into fatboy_hobby VALUES(null,"肥仔超","吃槟榔、养养猫","挨踢攻城狮","大上海");

好了,创建有了一个表的数据了,那么下面可以使用pymysql来进行增删查改的操作。

使用pymysql查询一行数据fetchone()# -*- coding: utf-8 -*-

from pymysql import *

def main():

# 创建Connection连接

conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')

# 获得Cursor对象

cs1 = conn.cursor()

# 执行select语句,并返回受影响的行数:查询一条数据

count = cs1.execute('select * from fatboy_hobby;')

# 打印受影响的行数

print("查询到%d条数据:" % count)

for i in range(count):

# 获取查询的结果

result = cs1.fetchone()

# 打印查询的结果

print(result)

# 获取查询的结果

# 关闭Cursor对象

cs1.close()

conn.close()

if __name__ == '__main__':

main()

运行如下:G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py

查询到3条数据:

(1, u'\u80d6\u5b50\u8001\u677f', u'\u6597\u5730\u4e3b', u'\u5c0f\u5356\u94fa\u8001\u677f', u'\u897f\u4e5d\u9f99')

(2, u'\u80a5\u4ed4\u767d', u'\u6253dota\u3001\u5403\u69df\u6994', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u94dc\u9523\u6e7e')

(3, u'\u80a5\u4ed4\u8d85', u'\u5403\u69df\u6994\u3001\u517b\u517b\u732b', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u5927\u4e0a\u6d77')

使用pymysql查询多行数据fetchall()# -*- coding: utf-8 -*-

from pymysql import *

def main():

# 创建Connection连接

conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')

# 获得Cursor对象

cs1 = conn.cursor()

# 执行select语句,并返回受影响的行数:查询一条数据

count = cs1.execute('select * from fatboy_hobby;')

# 打印受影响的行数

print("查询到%d条数据:" % count)

# for i in range(count):

# # 获取查询的结果

# result = cs1.fetchone()

# # 打印查询的结果

# print(result)

# # 获取查询的结果

result = cs1.fetchall()

print(result)

# 关闭Cursor对象

cs1.close()

conn.close()

if __name__ == '__main__':

main()

运行如下:查询到3条数据:

((1, u'\u80d6\u5b50\u8001\u677f', u'\u6597\u5730\u4e3b', u'\u5c0f\u5356\u94fa\u8001\u677f', u'\u897f\u4e5d\u9f99'), (2, u'\u80a5\u4ed4\u767d', u'\u6253dota\u3001\u5403\u69df\u6994', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u94dc\u9523\u6e7e'), (3, u'\u80a5\u4ed4\u8d85', u'\u5403\u69df\u6994\u3001\u517b\u517b\u732b', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u5927\u4e0a\u6d77'))

使用pymysql增加数据# -*- coding: utf-8 -*-

from pymysql import *

def main():

# 创建Connection连接

conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')

# 获得Cursor对象

cs1 = conn.cursor()

# 执行insert语句,并返回受影响的行数:添加一条数据

# 增加

count = cs1.execute('insert into fatboy_hobby VALUES(null,"肥仔白","打dota、吃槟榔","挨踢攻城狮","铜锣湾");')

#打印受影响的行数

print(count)

# 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交

conn.commit()

# 关闭Cursor对象

cs1.close()

conn.close()

if __name__ == '__main__':

main()

运行如下:G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py

1

Process finished with exit code 0

使用pymysql更新数据# -*- coding: utf-8 -*-

from pymysql import *

def main():

# 创建Connection连接

conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')

# 获得Cursor对象

cs1 = conn.cursor()

# 更新

count = cs1.execute('update fatboy_hobby set name="小肥仔是李白" where id="4"')

#打印受影响的行数

print(count)

# 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交

conn.commit()

# 关闭Cursor对象

cs1.close()

conn.close()

if __name__ == '__main__':

main()

运行如下:G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py

1

Process finished with exit code 0

使用pymysql删除数据# -*- coding: utf-8 -*-

from pymysql import *

def main():

# 创建Connection连接

conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')

# 获得Cursor对象

cs1 = conn.cursor()

# 删除

count = cs1.execute('delete from fatboy_hobby where id=4')

#打印受影响的行数

print(count)

# 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交

conn.commit()

# 关闭Cursor对象

cs1.close()

conn.close()

if __name__ == '__main__':

main()

运行如下:G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py

1

Process finished with exit code 0

参数化sql语句的参数化,可以有效防止sql注入

注意:此处不同于python的字符串格式化,全部使用%s占位# -*- coding: utf-8 -*-

from pymysql import *

def main():

# 创建Connection连接

conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')

# 获得Cursor对象

cs1 = conn.cursor()

# 构造参数列表

params = ["肥仔白"]

# 执行select语句,并返回受影响的行数:查询所有数据

count = cs1.execute('select * from fatboy_hobby where name=%s', params)

# 注意:

# 如果要是有多个参数,需要进行参数化

# 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可

# 打印受影响的行数

print(count)

# 获取查询的结果

result = cs1.fetchall()

print("result=%s" % result)

# 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交

conn.commit()

# 关闭Cursor对象

cs1.close()

conn.close()

if __name__ == '__main__':

main()

运行如下:G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py

1

result=(2, u'\u80a5\u4ed4\u767d', u'\u6253dota\u3001\u5403\u69df\u6994', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u94dc\u9523\u6e7e')

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值