python中的DB-API
为大多数数据库实现了接口,使用它链接数据库,就可使用相同的方式操做各数据库。
使用DB-API
基本流程python
API
模块。使用pymysql
(同时支持python2和3)做为链接mysql数据库的接口。直接使用pip install pymysql
安装便可。
注意:pip
安装以后使用pycharmimport pymysql
可能出现没法使用的状况,此时可直接在pycharm中安装pymysql
包。经过File–>Settings–>Project:XXX–>Project Interpreter能够看到全部已安装的包,点击右边绿色+
便可添加。
python2.X中还可使用MySQLdb
(仅支持python2),点击mysqldb可下载安装。mysql
事务是必须知足4个条件(ACID): Atomicity(原子性)、Consistency(稳定性)、Isolation(隔离性)、Durability(可靠性)。sql
autocommit
参数默认为开启,若须要多条sql语句同时提交,能够经过start transaction
开启事务,经过rollback
回滚事务,经过commit
提交事务。autocommit
参数状态:show variables like autocommit
。 8.0
,经常使用版本为5.6
和5.7
,能够根据本身须要选择合适版本。经常使用操做数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
受权超级用户 grant all privileges on *.* to 'user'@'%' identified by 'password' with grant option; 建立普通用户并受权 grant all on *.* to db1.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'; 更改密码 UPDATE mysql.user SET password=PASSWORD("newpwd") WHERE user='username' ; 查看库 show databases; 查看都有哪些库 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查询的才有 查询 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'; 执行sql mysql -uroot -p1234556 -e "select user,host,password into outfile '/home/mysql/1.txt' from mysql.user;"; |
数据库链接ide
1 |
conn=pymysql.connect(host="192.168.48.128",user="xiang",passwd="123456",db="python") |
参数说明
host:数据库主机名.默认是用本地主机。
user:数据库登录名.默认是当前用户。
passwd:数据库登录的秘密.默认为空。
db:要使用的数据库名.没有默认值。
port:MySQL服务使用的TCP端口.默认是3306,数字类型。函数
一个典型的执行过程fetch
1 2 3 4 5 6 7 8 9 10 |
import pymysql conn = pymysql.connect(host="192.168.48.136", port=3306, user="xiang", passwd="xiang", db="test") cus = conn.cursor() sql = "select * from test2;" cus.execute(sql) result = cus.fetchall() print(result) cus.close() conn.close() |
在实际编码过程当中,推荐经过函数形式调用,方便重复使用和修改。编码
1 2 3 4 5 6 7 8 9 10 11 12 |
def connect_mysql(): db_config = { 'host': '192.168.48.128', 'port': 3306, 'user': 'xiang', 'passwd': '123456', 'db': 'python', 'charset': 'utf8' } cnx = pymysql.connect(**db_config) return cnx |