Python中操作mysql知识(一)
Python 標(biāo)準(zhǔn)數(shù)據(jù)庫接口為 Python DB-API,Python DB-API為開發(fā)人員提供了數(shù)據(jù)庫應(yīng)用編程接口。
Python 數(shù)據(jù)庫接口支持非常多的數(shù)據(jù)庫,你可以選擇適合你項目的數(shù)據(jù)庫:
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
Python的DB-API,為大多數(shù)的數(shù)據(jù)庫實現(xiàn)了接口,使用它連接各數(shù)據(jù)庫后,就可以用相同 的方式操作各數(shù)據(jù)庫。
Python DB-API使用流程:
1.?? ?引入API模塊。
2.?? ?獲取與數(shù)據(jù)庫的連接。
3.?? ?執(zhí)行SQL語句和存儲過程。
4.?? ?關(guān)閉數(shù)據(jù)庫連接。
?
什么是MySQLdb?
MySQLdb 是用于Python鏈接Mysql數(shù)據(jù)庫的接口,它實現(xiàn)了 Python 數(shù)據(jù)庫 API 規(guī)范 V2.0,基于 MySQL C API 上建立的。
如何安裝MySQLdb?
為了用DB-API編寫MySQL腳本,必須確保已經(jīng)安裝了MySQL。復(fù)制以下代碼,并執(zhí)行:
如果執(zhí)行后的輸出結(jié)果如下所示,意味著你沒有安裝 MySQLdb 模塊:
安裝MySQLdb,請訪問 http://sourceforge.net/projects/mysql-python ,(Linux平臺可以訪問:https://pypi.python.org/pypi/MySQL-python)從這里可選擇適合您的平臺的安裝包,分為預(yù)編譯的二進(jìn)制文件和源代碼安裝包。
如果您選擇二進(jìn)制文件發(fā)行版本的話,安裝過程基本安裝提示即可完成。如果從源代碼進(jìn)行安裝的話,則需要切換到MySQLdb發(fā)行版本的頂級目錄,并鍵入下列命令:
pip好像是不支持安裝MySQLdb的,我們可以通過網(wǎng)站下載安裝,
下載地址:https://pypi.python.org/pypi/MySQL-python/1.2.5
分別對應(yīng)有windows和源碼安裝的方法
安裝依賴包:
yum?install?–y?python-devel yum?install?–y?mysql-devel yum?install?–y?gccPython3以后好像是不支持MySQLdb了,可以是用pymysql包,
可以直接通過pymysql進(jìn)行使用。
MySQLdb 只適用于python2.x,發(fā)現(xiàn)pip裝不上。它在py3的替代品是: import pymysql
?
Mysql的事務(wù)
一般來說,事務(wù)是必須滿足4個條件(ACID): Atomicity(原子性)、Consistency(穩(wěn)定性)、Isolation(隔離性)、Durability(可靠性)
1、事務(wù)的原子性:一組事務(wù),要么成功;要么撤回。
2、穩(wěn)定性 : 有非法數(shù)據(jù)(外鍵約束之類),事務(wù)撤回。
3、隔離性:事務(wù)獨立運(yùn)行。一個事務(wù)處理后的結(jié)果,影響了其他事務(wù),那么其他事務(wù)會撤回。事務(wù)的100%隔離,需要犧牲速度。
4、可靠性:軟、硬件崩潰后,InnoDB數(shù)據(jù)表驅(qū)動會利用日志文件重構(gòu)修改。可靠性和高速度不可兼得, innodb_flush_log_at_trx_commit選項 決定什么時候吧事務(wù)保存到日志里
?
安裝Mysql
1.上官網(wǎng),下源碼包
?
2.安裝依賴工具:
yum?-y?install?make?gcc-c++?cmake?bison-devel?ncurses-devel?libaio?libaio-devel?perl-Data-Dumper?net-tools3. 解壓
rzcd?/usr/local/srctar?xzvf?mysql-5.6.32.tar.gzcd?mysql-5.6.324.編譯:
cmake?-DCMAKE_INSTALL_PREFIX=/export/servers/mysql/?-DMYSQL_DATADIR=/export/Data/mysql/data?-DSYSCONFDIR=/export/servers/mysql/etc?-DWITH_INNOBASE_STORAGE_ENGINE=1?-DWITH_PERFSCHEMA_STORAGE_ENGINE=1?-DDEFAULT_CHARSET=utf8?-DDEFAULT_COLLATION=utf8_general_ci?-DMYSQL_UNIX_ADDR=/export/Data/mysql/tmp/mysql.sock?-DENABLED_LOCAL_INFILE=ON?-DENABLED_PROFILING=ON?-DWITH_DEBUG=0?-DMYSQL_TCP_PORT=3358?
DCMAKE_INSTALL_PREFIX | /usr/local/mysql | 安裝目錄 |
DMYSQL_DATADIR | /usr/local/mysql/data | 數(shù)據(jù)庫位置 |
DSYSCONFDIR | /etc | 配置文件位置 |
DWITH_MYISAM_STORAGE_ENGINE | 1 | 安裝myisam存儲引擎 |
DWITH_INNOBASE_STORAGE_ENGINE | 1 | 安裝innodb存儲引擎 |
DWITH_MEMORY_STORAGE_ENGINE | 1 | 安裝memory存儲引擎 |
DWITH_READLINE | 1 | 快捷鍵功能 |
DMYSQL_UNIX_ADDR | /var/lib/mysql/mysql.sock | Unix socket 文件路徑 |
DMYSQL_TCP_PORT | 3306 | MySQL監(jiān)聽端口 |
DENABLED_LOCAL_INFILE | 1 | 許從本地導(dǎo)入數(shù)據(jù)- |
DWITH_PARTITION_STORAGE_ENGINE | 1 | 安裝數(shù)據(jù)庫分區(qū) |
DEXTRA_CHARSETS | all | 安裝所有擴(kuò)展字符集 |
DDEFAULT_CHARSET | utf8 | 使用utf8字符 |
DDEFAULT_COLLATION | utf8_general_ci | 校驗字符 |
如圖所示編譯成功,每次進(jìn)行echo $?進(jìn)行驗證
make?&&?make?install5.創(chuàng)建mysql用戶=并賦權(quán)
useradd?mysql?-s?/sbin/nologinchown?-R?mysql:mysql?/export/servers/mysql?/export/Data/mysql6.初始化系統(tǒng)表:
cd?/export/servers/mysql/scripts./mysql_install_db?--basedir=/export/servers/mysql/?--datadir=/export/Data/mysql/data?--user=mysqlmkdir?-p?/export/servers/mysql/etccp?/export/servers/mysql/my.cnfyum?remove?-y?mysql7.啟動mysql
cd?/export/servers/mysqlcp?support-files/mysql.server?/etc/init.d/mysqld檢查配置文件的datadir,basedir等是否正確
service?mysqld?start8.檢查mysql是否啟動成功
ps?-ef?|grep?mysqlnetstat?-lnp?|grep?mysql9.如果啟動不了,就在/export/Data/mysql/data找`hostname`.err對應(yīng)的日志查看
Mysql常用操作
?授權(quán)超級用戶:
?grant all privileges on *.* to 'fengxiaoqing'@'%' identified by 'admin@123' with grant option;
?查看庫:
?show databases;
?查看都有哪些庫? show databases;
?查看某個庫的表 use db; show tables \G;
?查看表的字段 desc tb;
?查看建表語句 show create table tb;
?當(dāng)前是哪個用戶? select user();
?當(dāng)前庫 select database();
?創(chuàng)建庫 create database db1;
?創(chuàng)建表 create table t1 (id int, name char(40) adress varchar(30));?
?char(10)????????????? 'aaa?????? '
?varchar(10)????????? 'aaa'
?查看數(shù)據(jù)庫版本 select version();
?查看mysql狀態(tài) show status;
?修改mysql參數(shù) 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查詢的才有
?創(chuàng)建普通用戶并授權(quán) 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,'feng');
?更改密碼 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;
?刪除數(shù)據(jù)庫 drop database db1;
?修復(fù)表 repair table tb1 [use frm];
?查看權(quán)限show grants for root@'localhost';
?echo "select user,host,password from mysql.user" |mysql -uroot -p123456
?mysql -uroot -p1234556 -e "select user,host,password into outfile '/home/mysql/1.txt' from mysql.user;"
Mysql的連接
?1.創(chuàng)建數(shù)據(jù)庫 create database python;
?2. 授權(quán)用戶
?grant all privileges on *.* to feng@’%’ identified by ‘123456’;
?flush privilege;
?conn=MySQLdb.connect(host="192.168.100.101",user="feng",passwd="123456",db="python",charset="utf8")
?
比較常用的參數(shù)包括:
?host:數(shù)據(jù)庫主機(jī)名.默認(rèn)是用本地主機(jī)
?user:數(shù)據(jù)庫登陸名.默認(rèn)是當(dāng)前用戶
?passwd:數(shù)據(jù)庫登陸的秘密.默認(rèn)為空
?db:要使用的數(shù)據(jù)庫名.沒有默認(rèn)值
?port:MySQL服務(wù)使用的TCP端口.默認(rèn)是3306,數(shù)字類型
?charset:數(shù)據(jù)庫編碼
?
推薦大家使用函數(shù)的方式:
def?connect_mysql():????db_config?=?{'host':?'192.168.48.128','port':?3306,'user':?'xiang','passwd':?'123456','db':?'python','charset':?'utf8'????}cnx?=?MySQLdb.connect(**db_config)return?cnx?
游標(biāo)
游標(biāo)(Cursor)是處理數(shù)據(jù)的一種方法,為了查看或者處理結(jié)果集中的數(shù)據(jù),游標(biāo)提供了在結(jié)果集中一次一行或者多行前進(jìn)或向后瀏覽數(shù)據(jù)的能力。可以把游標(biāo)當(dāng)作一個指針,它可以指定結(jié)果中的任何位置,然后允許用戶對指定位置的數(shù)據(jù)進(jìn)行處理
Import…………if?__name__?==?'__main__':cnx?=?connect_mysql()cus?=?cnx.cursor()sql??=?'''?create?table?test(id?int?not?null);insert?into?test(id)?values?(100);'''????try:cus.execute(sql)cus.close()cnx.commit()except?Exception?as?e:cnx.rollback()print('Error')#?raise?e????finally:cnx.close()游標(biāo)常用的方法:
常用方法:
cursor():創(chuàng)建游標(biāo)對象
Cus = connect_mysql().cursour()
close():關(guān)閉此游標(biāo)對象
excute(sql[, args]):執(zhí)行一個數(shù)據(jù)庫查詢或命令
fetchone():得到結(jié)果集的下一行
fetchmany([size = cursor.arraysize]):得到結(jié)果集的下幾行
fetchall():得到結(jié)果集中剩下的所有行
executemany (sql, args):執(zhí)行多個數(shù)據(jù)庫查詢或命令
個人推薦,盡量不使用executemany,通過程序循環(huán)不斷調(diào)用excute函數(shù)
?
數(shù)據(jù)庫連接池
import?pymysqlfrom?DBUtils.PooledDB?import?PooledDBfrom?DBUtils.PooledDB?import?PooledDBdb_config?=?{"host":?"192.168.48.131","port":?3306,"user":?"xiang","passwd":?"xiang","db":?"python",#?"charset":?"utf8"????}spool = PooledDB(pymysql, 5, **db_config) ?# 5為連接池里的最少連接數(shù)
# def connect_myssql():
conn = spool.connection() ?# 以后每次需要數(shù)據(jù)庫連接就是用connection()函數(shù)獲取連接
cur = conn.cursor()
SQL = "select * from tmp;"
r = cur.execute(SQL)
r = cur.fetchall()
print(r)
cur.close()
conn.close()
?
轉(zhuǎn)載于:https://blog.51cto.com/fengyunshan911/2114920
總結(jié)
以上是生活随笔為你收集整理的Python中操作mysql知识(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nginx+tomcat的keepali
- 下一篇: 在MySQL中使用explain查询SQ