安装
安装MySQL的接口主要是有几种方式:
https://pypi.python.org/pypi/mysql-connector-python
纯python 有点慢而且和MySQLdb不兼容https://pypi.python.org/pypi/pymysql
纯python但是比1块,几乎和MySQLdb兼容 (用pymysql.install_as_MySQLdb())
python3 -m pip install PyMySQL
创建数据库并用pymysql操作数据库的简单例子看本文后面
- https://pypi.python.org/pypi/mysqlclient
Django的推荐库,是MySQLdb的fork, C实现很快,和MySQLdb兼容
这个稍微麻烦点了:
首先你得装python3
接下来安装mysql:
brew install mysql
如果homebrew都没有装的话先装下:
sudo chown -R $USER:admin /usr/local/*
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
搞好之后会看到几条之后用的命令
We've installed your MySQL database without a root password. To secure it run:
mysql_secure_installation
MySQL is configured to only allow connections from localhost by default
To connect run:
mysql -uroot
To have launchd start mysql now and restart at login:
brew services start mysql
Or, if you don't want/need a background service you can just run:
mysql.server start
mysql装好后接下来执行:
export PATH=$PATH:/usr/local/mysql/bin
最后
pip3 install mysqlclient
这个时候遇到错了:
查了很多资料还是解决不了这个问题。。。
最后使用了conda来装居然成功了。。
conda install mysqlclient
管理MySQL数据库
主要参考https://dev.mysql.com/doc/mysql-getting-started/en/
和https://dev.mysql.com/doc/refman/8.0/en/creating-accounts.html
第一次进入MySQL:
mysql.server start
然后用root身份登录
mysql -u root -p
默认没有password直接回车
然后进入之后可以修改密码,假如root的身份的密码就是root:
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
quit可以退出,重新登录之后几个常见的命令:
SHOW processlist; # 展示所有的进程列表
kill ; # 杀掉进程(遇到“Lock wait timeout exceeded; try restarting transaction”问题的最后一招)
SHOW DATABASES; 展示所有数据库
CREATE DATABASE pets; 这个是创建一个pets的数据库
USE pets; 创建table之前需要做的
具体创建一个名为cats的表的例子:
CREATE TABLE cats
(
id INT unsigned NOT NULL AUTO_INCREMENT, # Unique ID for the record
name VARCHAR(150) NOT NULL, # Name of the cat
owner VARCHAR(150) NOT NULL, # Owner of the cat
birth DATE NOT NULL, # Birthday of the cat
PRIMARY KEY (id) # Make the id the primary key 主键自动增加
);
SHOW TABLES; 展示表
DESCRIBE cats; 显示cats这个表的所有列的属性
SHOW CREATE TABLE cats 这个还要展示得更详细
插入3条记录到cats表中:
INSERT INTO cats ( name, owner, birth) VALUES
( 'Sandy', 'Lennon', '2015-01-03' ),
( 'Cookie', 'Casey', '2013-11-13' ),
( 'Charlie', 'River', '2016-05-21' );
SELECT name FROM cats WHERE owner = 'Casey'; 查询
DELETE FROM cats WHERE name='Cookie'; 删除
增删表的某列,例如增加一个叫gender的列:
ALTER TABLE cats ADD gender CHAR(1) AFTER name;
关于super-user的管理:
创建一个用户叫做finley,密码设置为password, 给所有超级权限
CREATE USER 'finley'@'localhost'
-> IDENTIFIED BY 'password';
GRANT ALL
-> ON *.*
-> TO 'finley'@'localhost'
-> WITH GRANT OPTION;
查看的话可以用:
show grants for 'finley'@'localhost';
创建一个用户叫做custom,密码设置为password, 给pets数据库下的所有权限
CREATE USER 'custom'@'localhost'
-> IDENTIFIED BY 'password';
GRANT ALL
-> ON pets.*
-> TO 'custom'@'localhost';
用PyMySQL操作数据库
可以参见https://pypi.org/project/PyMySQL/,我这里提供一个完整例子,操作刚才上一个部分新建好的pets数据库中的cats表格,插入一条数据,并打印出表中所有的记录。
import pymysql
pymysql.install_as_MySQLdb()
import datetime
con = pymysql.connect('localhost', 'custom', 'password', 'pets')
# 插入一条数据,因为最后是个date类型的,所以我先换成string的才能插进去
now = datetime.date(2020, 5, 1)
formatted_date = now.strftime('%Y-%m-%d') # e.g.输出的formatted_date会是'2020-05-01'
try:
with con.cursor() as cursor:
# 创建一条新的记录
sql = "INSERT INTO cats (name,owner,birth) VALUES (%s, %s, %s)"
cursor.execute(sql, ('Miao', 'Gong', formatted_date))
# connection is not autocommit by default. So you must commit to save
# your changes.连接并不是自动commit的 所以必须要手动做这一步去存下来这个操作
con.commit()
# 返回所有记录
with con.cursor() as cursor:
sql = "SELECT * from cats"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
finally:
con.close()
最后打印出来的结果如下,可以看到已经成功插入了,成为第四条记录:
((1, 'Sandy', 'Lennon', datetime.date(2015, 1, 3)), (2, 'Cookie', 'Casey', datetime.date(2013, 11, 13)), (3, 'Charlie', 'River', datetime.date(2016, 5, 21)), (4, 'Miao', 'Gong', datetime.date(2020, 5, 1)))
用MySQLDB操作数据库
import MySQLdb
conn = MySQLdb.connect(host='localhost',user="finley",passwd= 'password',db='pets')
cur = conn.cursor()
#创建数据表
cur.execute("create table owner(id int ,name varchar(15), hobby varchar(30),age varchar(10))")
#插入一条数据
cur.execute("insert into owner values(4,'Lennon4','football4','43')")
#删除一条数据
cur.execute("delete from owner where name = 'Lennon'")
#修改查询条件的数据
#cur.execute("update owner set hobby ='football, basketball2' where name = 'Lennon'")
cur.close()
conn.commit() # 这个才会去执行
conn.close()
如果遇到# Authentication plugin 'caching_sha2_password' cannot be loaded
的问题,就改变下加密的方式:
ALTER USER 'yourusername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'youpassword';