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 |