您的位置:首页 > 编程语言 > Python开发

Python数据库之--PyMySQL

2017-12-07 20:00 316 查看
一、Python3中使用PyMySql

1、 直接命令:pip install pymysql

2、 测试 pip show pymysql



二、创建MySQL表
执行下面的SQL语句,创建一张users 表。
CREATE
TABLE `users` (
    `id` INT(11)
NOT NULL AUTO_INCREMENT,
    `email`
VARCHAR(255) COLLATE utf8_bin
NOT NULL,
    `password`
VARCHAR(255) COLLATE utf8_bin
NOT NULL,
    PRIMARY
KEY (`id`)
) ENGINE=INNODB
DEFAULT CHARSET=utf8COLLATE=utf8_bin
AUTO_INCREMENT=1 ;
 
 
 
三、Python操作MySQL
接下来才是重点,Python操作MySQL数据库。
3.1插入数据:
import pymysql.cursors
 
#
连接MySQL数据库
connection =pymysql.connect(host='127.0.0.1', port=3306, user='root',password='198876', db='guest',

                             charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
 
#
通过cursor创建游标
cursor = connection.cursor()
 
#
创建sql 语句,并执行
sql = "INSERT INTO `users` (`email`,`password`) VALUES ('huzhiheng@itest.info', '123456')"
cursor.execute(sql)
 
#
提交SQL
connection.commit()
 
  不管你使用的是什么工具或库,连接数据库这一步必不可少。host为数据库的主机IP地址,port为MySQL的默认端口号,user为数据的用户名,password为数据库的登录密码,db为数据库的名称。
cursor()方法创建数据库游标。
execute()方法执行SQL语句。
commit()将数据库的操作真正的提交到数据。
 
3.2. 查询数据
import pymysql.cursors
 
 
#
连接MySQL数据库
connection =pymysql.connect(host='127.0.0.1', port=3306, user='root',password='198876', db='guest',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
 
 
#
通过cursor创建游标
cursor =connection.cursor()
 
#
执行数据查询
sql = "SELECT `id`, `password` FROM `users`WHERE `email`='huzhiheng@itest.info'"
cursor.execute(sql)
 
#查询数据库单条数据
result =cursor.fetchone()
print(result)
 
print("-----------华丽分割线------------")
 
#
执行数据查询
sql = "SELECT `id`, `password` FROM`users`"
cursor.execute(sql)
 
#查询数据库多条数据
result =cursor.fetchall()
for data
inresult:
    #查询结果是一个字典,通过关键字来获取值
    id = data[“id”]
    password = data[“password”]
    print(id,password)
 
 
#
关闭数据连接
connection.close()
 
   接下来的操作就是数据库的查询了。
fetchone() 用于查询单条数据。
fetchall() 用于查询多条数据。
close() 最后不要忘记了关闭数据连接。
  运行结果:
{'password':
'123456', 'id': 1}
-----------华丽分割线------------
{'password':
'123456', 'id': 1}
{'password':
'654321', 'id': 2}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: