python 连接MySQL

1.Python DB-API

Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同 的方式操作各数据库。

Python DB-API使用流程:
1. 引入API模块。
2. 获取与数据库的连接。
3. 执行SQL语句和存储过程。

4. 关闭数据库连接。

2.MySQL

MySQL是Web世界中使用最广泛的数据库服务器。是为服务器端设计的数据库,能承受高并发访问,MySQL内部有多种数据库引擎,最常用的引擎是支持数据库事务的InnoDB。

(1)MySQL的事务

一般来说,事务是必须满足4个条件(ACID): Atomicity(原子性)、Consistency(稳定性)、Isolation(隔离性)、Durability(可靠性)
1、事务的原子性:一组事务,要么成功;要么撤回。
2、稳定性 : 有非法数据(外键约束之类),事务撤回。
3、隔离性:事务独立运行。一个事务处理后的结果,影响了其他事务,那么其他事务会撤回。事务的100%隔离,需要牺牲速度。

4、可靠性:软、硬件崩溃后,InnoDB数据表驱动会利用日志文件重构修改。可靠性和高速度不可兼得, innodb_flush_log_at_trx_commit选项 决定什么时候吧事务保存到日志里

查询MySQL自动提交:autocommit

mysql> show variables like 'auto%';

+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
| autocommit               | ON    |
| automatic_sp_privileges  | ON    |
+--------------------------+-------+
(2)MySQL的常用操作

授权超级用户:
grant all privileges on *.* to 'tangnanbing'@'%' identified by '1qaz@WSX' with grant option;
查看都有哪些库  show databases;
查看某个库的表 use db; show tables \G; 
查看表的字段 desc tb;
查看建表语句 show create table tb;
当前是哪个用户  select user();
当前库 select database();
创建库 create database db1; 
创建表 create table t1 (id int, name char(40),adress varchar(30));  
查看数据库版本 select version(); 
查看mysql状态 show status;
修改mysql参数 show variables like 'max_connect%'; set global max_connect_errors = 1000; 
查看mysql队列 show processlist; 
select * from information_schema.processlist where info is not null;
sleep的可以忽略,qurey查询的才有
创建普通用户并授权 grant all on *.* to databases1.user1 identified by '123456'; 
grant all on db1.* to 'user2'@'10.0.2.100' identified by '111222'; 
grant all on db1.* to 'user3'@'%' identified by '231222';insert into tb1 (id,name) values(1,'aming');
更改密码 UPDATE mysql.user SET password=PASSWORD("newpwd") WHERE user='username' ;   
查询 select count(*) from mysql.user; select * from mysql.db; select * from mysql.db where host like '10.0.%'; 
插入 update db1.t1 set name='aaa' where id=1;  
清空表 truncate table db1.t1; 
删除表 drop table db1.t1; 
删除数据库 drop database db1; 
修复表 repair table tb1 [use frm];
查看权限show grants for root@'localhost';
查询表中的字段 echo "select user,host,password from mysql.user" |mysql -uroot -ppwd
将查询到的信息导出到文件中 mysql -uroot -p1234556 -e "select user,host,password into outfile '/home/mysql/1.txt' from mysql.user;";

扫描二维码关注公众号,回复: 875422 查看本文章

3.连接MySQL使用的包

(1)MySQLdb

 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。

我们可以通过网站下载安装,下载地址:https://pypi.org/project/MySQL-python/1.2.5/#files   

分别对应有windows和源码安装的方法。

(2)pymysql

python3以后是不支持MySQLdb了,但是可以使用pymysql包,可以直接通过pymysql进行连接。
pip install pymysql

mysqldb 与 pymsql在用法上几乎相同,只是前者支持python2,后者支持python3,所以根据自己的版本使用就行了。

4.连接实例

Python 数据库图解流程


Connection、Cursor比喻


(1)Connection()

Connection()的参数:

host:数据库主机名.默认是用本地主机
port:MySQL服务使用的TCP端口.默认是3306,数字类型
user:数据库登陆名.默认是当前用户
password:数据库登陆的秘密.默认为空
db:要使用的数据库名.没有默认值
charset:数据库编码

(2)cursor()
cursor就是一个Cursor对象,这个cursor是一个实现了迭代器(def__iter__())和生成器(yield)的MySQLdb对象,这个时候cursor中还没有数据,只有等到fetchone()或fetchall()的时候才返回一个元组tuple,才支持len()和index()操作,这也是它是迭代器的原因。但同时为什么说它是生成器呢?因为cursor只能用一次,即每用完一次之后记录其位置,等到下次再取的时候是从游标处再取而不是从头再来,而且fetch完所有的数据之后,这个cursor将不再有使用价值了,即不再能fetch到数据了。


常用方法:

close():关闭此游标对象
fetchone():得到结果集的下一行
fetchmany(size):得到结果集的下几行
fetchall():得到结果集中剩下的所有行
excute(sql[, args]):执行一个数据库查询或命令
excutemany(sql, args):执行多个数据库查询或命令


(3)连接测试

在连接之前我们要先在数据库上授权一个用户,让它可以登录:

授权用户 grant all privileges on *.* to sixgod@"%" identified by "123456";

               flush privileges;

授权之后就可以用这个用户来进行连接了。


conn = pymsql.connect(host='localhost',port = 3306,user='sixgod', passwd='123456',db ='test')

#Connect() 方法用于创建数据库的连接,里面指定参数:用户名,密码,主机等信息。


cur=conn.cursor()  #通过获取到的数据库连接conn下的cursor()方法来创建游标。

cur.execute("show databases;")
#通过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写入sql语句来对数据进行操作。

data =cur.fetchall() #获取查询到数据
print(date) #将数据打印

cur.commit()#如果是向数据库插入一条数据后,必须使用该命令,否则数据不会被真正的写入。
cur.close() #关闭游标

conn.close() #关闭数据库连接


使用pycharm编辑器连接:
import pymysql

conn = pymysql.connect(host="location",port=3306,user="sixgod",password="123456",db="test")
cur = conn.cursor()

cur.execute("show tables;")
data = cur.fetchall()
print(data)

cur.close()
conn.close()
结果为:(('sixgod',), ('text',))
可以看到已经正确连接,并且可以进行相关查询。

当插入数据时可以这样写:
import pymysql

conn = pymysql.connect(host="location",port=3306,user="sixgod",password="123456",db="test")
cur = conn.cursor()

try:
    cur.execute("insert into sixgod(id,name) values(3,'a');") # 执行sql语句
    conn.commit()  # 提交到数据库执行
except:
   conn.rollback() # 如果发生错误则回滚

cur.close()#关闭游标
conn.close()#释放数据库资源



猜你喜欢

转载自blog.csdn.net/weixin_39318540/article/details/80215730