標籤:python mysql
Python裡面操作MySQL可以通過兩個方式:
-
pymysql模組
-
ORM架構的SQLAchemey
本節先學習第一種方式。
學習Python模組之前,首先看看MySQL的基本安裝和使用,具體文法可以參考豆子之前的部落格http://beanxyz.blog.51cto.com/5570417/1609972
或者官方簡介
https://mariadb.com/kb/en/mariadb/basic-sql-statements/
簡單的回顧一下基本環境的搭建:
首先安裝Mariadb(我的環境是CentOS7)
yum install mariadb*systemctl start mariadb
配置防火牆
firewall-cmd --add-port=3306/tcp --permanentsystemctl restart firewalld
配置root密碼
mysqladmin -u root password ‘mysql‘mysql -uroot -p
建立一個測試用的資料庫和表
MariaDB [(none)]> create database mydb;Query OK, 1 row affected (0.00 sec)MariaDB [(none)]> use mydbDatabase changedMariaDB [mydb]> create table student(id int not null auto_increment,name varchar(10), primary key(id));Query OK, 0 rows affected (0.04 sec)MariaDB [mydb]> insert into student(name) values(‘Jay‘),(‘Bob‘),(‘Alex‘);Query OK, 3 rows affected (0.00 sec)Records: 3 Duplicates: 0 Warnings: 0MariaDB [mydb]> select * from student;+----+------+| id | name |+----+------+| 1 | Jay || 2 | Bob || 3 | Alex |+----+------+3 rows in set (0.00 sec)
建立一個遠端存取的賬戶
MariaDB [(none)]> create user [email protected];Query OK, 0 rows affected (0.00 sec)MariaDB [(none)]> set password for [email protected]‘10.2.100.60‘=password(‘yli‘);Query OK, 0 rows affected (0.01 sec)MariaDB [(none)]> grant all privileges on mydb.* to [email protected];Query OK, 0 rows affected (0.00 sec)
然後安裝一個圖形介面的工具Navicat,綁定資料庫
650) this.width=650;" src="http://s4.51cto.com/wyfs02/M00/89/F0/wKioL1gij7nxF_w0AADPQRGw3qE012.png" style="float:none;" title="1.PNG" alt="wKioL1gij7nxF_w0AADPQRGw3qE012.png" />
650) this.width=650;" src="http://s5.51cto.com/wyfs02/M01/89/F3/wKiom1gij7rh9UoaAADlgxB33VI628.png" style="float:none;" title="2.PNG" alt="wKiom1gij7rh9UoaAADlgxB33VI628.png" />
這樣一個基本的測試環境就搭建好了。
現在來看看pymysql的使用。
在我的用戶端安裝一下pymysql的模組
C:\WINDOWS\system32>pip install pymysqlCollecting pymysql Downloading PyMySQL-0.7.9-py3-none-any.whl (78kB) 100% |################################| 81kB 610kB/sInstalling collected packages: pymysqlSuccessfully installed pymysql-0.7.9
Python源碼示範
查詢
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysql#開啟資料庫連接conn = pymysql.connect(host=‘sydnagios‘, port=3306, user=‘yli‘, passwd=‘yli‘, db=‘mydb‘)#建立一個遊標對象cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#SQL查詢cursor.execute("select * from student")# 擷取第一行資料# row_1 = cursor.fetchone()# print(row_1)# 擷取前n行資料# row_2 = cursor.fetchmany(3)# 擷取所有資料row_3 = cursor.fetchall()print(row_3)#scroll可以使用相對位置或者絕對位置,這裡相對位置(末尾)向上移動2行cursor.scroll(-2,mode=‘relative‘)row_3 = cursor.fetchall()print(row_3)#提交,不然無法儲存新的資料conn.commit()#關閉遊標cursor.close()#關閉串連conn.close()-----------[{‘id‘: 1, ‘name‘: ‘Jay‘}, {‘id‘: 2, ‘name‘: ‘Bob‘}, {‘id‘: 3, ‘name‘: ‘Alex‘}][{‘id‘: 2, ‘name‘: ‘Bob‘}, {‘id‘: 3, ‘name‘: ‘Alex‘}]
修改
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysqlconn = pymysql.connect(host=‘sydnagios‘, port=3306, user=‘yli‘, passwd=‘yli‘, db=‘mydb‘)cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute("Update student set name=‘BoB‘ where id=2")cursor.execute("select * from student")row_3 = cursor.fetchall()print(row_3)conn.commit()cursor.close()conn.close()----------[{‘id‘: 1, ‘name‘: ‘Chris‘}, {‘id‘: 2, ‘name‘: ‘BoB‘}, {‘id‘: 3, ‘name‘: ‘Alex‘}]
刪除
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysqlconn = pymysql.connect(host=‘sydnagios‘, port=3306, user=‘yli‘, passwd=‘yli‘, db=‘mydb‘)cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute("delete from student where id=2")cursor.execute("select * from student")row_3 = cursor.fetchall()print(row_3)conn.commit()cursor.close()conn.close()----------[{‘id‘: 1, ‘name‘: ‘Chris‘}, {‘id‘: 2, ‘name‘: ‘BoB‘}, {‘id‘: 3, ‘name‘: ‘Alex‘}]
添加
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysqlconn = pymysql.connect(host=‘sydnagios‘, port=3306, user=‘yli‘, passwd=‘yli‘, db=‘mydb‘)cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute("insert into student(name) value (‘ZhangSan‘),(‘LiSi‘)")cursor.execute("select * from student")row_3 = cursor.fetchall()print(row_3)conn.commit()cursor.close()conn.close()----------[{‘name‘: ‘Chris‘, ‘id‘: 1}, {‘name‘: ‘Alex‘, ‘id‘: 3}, {‘name‘: ‘ZhangSan‘, ‘id‘: 4}, {‘name‘: ‘LiSi‘, ‘id‘: 5}]
本文出自 “麻婆豆腐” 部落格,請務必保留此出處http://beanxyz.blog.51cto.com/5570417/1871039
Python 學習筆記 - 操作MySQL