今天学习一下mysql,在python3中利用pymysql模块来操做。
先安装包:pip install PyMySQL
python
一、语法格式 *对象名 = pymysql.connect("主机地址","用户名","密码","库名","端口号") 二、connect链接对象支持的方法 *一、cursor() 建立一个游标对象db.cursor() *二、commit() 提交到数据库执行(表记录增删改) 三、rollback() 回滚 四、close() 关闭数据库链接 三、游标对象支持的方法 *一、execute("SQL命令") 执行SQL命令 二、fetchone() 取得结果集的第一条记录 三、fetchmany(n) 取得结果集的 n 条记录 *四、fetchall() 取得结果集的全部记录 五、close() 关闭游标对象
py {.line-numbers} import pymysql # 创建链接 # db = pymysql.connect(host=, user=, password=, database=, port=) db = pymysql.connect("xxxxx.com", "root", "mysq1112", "MyDB", xxxxx) # 建立游标对象 cur = db.cursor()
mysql
py {.line-numbers} cur.execute('SELECT VERSION()') data = cur.fetchone() print(f"Database version :{data}")
sql
py {.line-numbers} # creat table test sql_create = '''create table test(id INT(8) , name VARCHAR(20) , age INT(3) , value INT(3) )''' cur.execute(sql_create) cur.connection.commit() # insert table test sql_insert = 'INSERT INTO test(id, name, age, value) VALUES (10002, "docker", 15, 87)' cur.execute(sql_insert) cur.connection.commit()
docker
py {.line-numbers} # create table students sql_create = '''CREATE TABLE students( `id` bigint(20) NOT NULL AUTO_INCREMENT, `class_id` bigint(20) NOT NULL, `name` varchar(100) NOT NULL, `gender` varchar(1) NOT NULL, `score` int(11) NOT NULL, PRIMARY KEY (`id`) ) ''' cur.execute(sql_create) # insert table students list = [(1,1,'小明','M',90), (2,1,'小红','F',95), (3,1,'小军','M',88), (4,1,'小米','F',73), (5,2,'小白','F',81), (6,2,'小兵','M',55), (7,2,'小林','M',85), (8,3,'小新','F',91), (9,3,'小王','M',89), (10,3,'小丽','F',88)] for i in list: sql_inserts = f'INSERT INTO students(id, class_id, name, gender, score) VALUES {i}' print(sql_inserts) cur.execute(sql_inserts) cur.connection.commit()
数据库
py {.line-numbers} sql_select = '''select * from Writers''' cur.execute(sql_select) result = cur.fetchall() print(f"select * from:{result}")
函数
py {.line-numbers} cur.execute('drop database <database_name>') cur.execute('drop table <table_name>')
学习
db.close()
fetch
cur.execute('SQL语句') print(cur.fetchall())
sql {.line-numbers} -- 按AND条件查询students SELECT * FROM students WHERE score >= 80 AND gender = 'M' -- 按OR条件查询students SELECT * FROM students WHERE score >= 80 OR gender = 'M' -- 按NOT条件查询students SELECT * FROM students WHERE NOT class_id = 2 -- 按多个条件查询students SELECT * FROM students WHERE (score < 80 OR score > 90) AND gender = 'M' -- 排序test SELECT id, name, gender, score FROM students ORDER BY id; -- desc 倒序 SELECT id, name, gender, score FROM students ORDER BY id DESC; -- ASC升序 DESC降序 SELECT id, name, gender, score FROM students ORDER BY gender, score;
3d
py {.line-numbers} def fun1(pageSize, pageIndex): limit = pageSize offset = pageSize * (pageIndex - 1) print(f'limit:{limit},offset:{offset}') cur.execute(f''' SELECT id, name, gender, score FROM students ORDER BY id LIMIT {limit} OFFSET {offset} ''') print(cur.fetchall()) fun1(3,4)
code
py {.line-numbers} cur.execute(''' SELECT COUNT(*) boys FROM students WHERE gender = 'M' ''') print(cur.fetchall())
函数名 | 功能 |
---|---|
SUM | 计算某一列的合计值,该列必须为数值类型 |
AVG | 计算某一列的平均值,该列必须为数值类型 |
MAX | 计算某一列的最大值 |
MIN | 计算某一列的最小值 |
py {.line-numbers} cur.execute(''' SELECT COUNT(*) boys FROM students GROUP BY class_id ''') print(cur.fetchall())
py {.line-numbers} cur.execute(''' SELECT class_id, gender, COUNT(*) num FROM students GROUP BY class_id, gender; ''') print(cur.fetchall())
cur.execute(''' SELECT * FROM students, classes; ''')
cur.execute(''' SELECT s.id sid, s.name, s.gender, s.score, c.id cid, c.name cnameo FROM students s, classes c WHERE s.gender = 'M' AND c.id = 1; ''')
# 链接查询 cur.execute(''' SELECT s.id, s.name, s.class_id, c.name class_name, s.gender, s.score FROM students s INNER JOIN classes c ON s.class_id = c.id ''') print(cur.fetchall())
1.先肯定主表,仍然使用FROM <表1>的语法; 2.再肯定须要链接的表,使用INNER JOIN <表2>的语法; 3.而后肯定链接条件,使用ON <条件...>,这里的条件是s.class_id = c.id,表示students表的class_id列与classes表的id列相同的行须要链接; 4.可选:加上WHERE子句、ORDER BY等子句。
SELECT ... FROM tableA ??? JOIN tableB ON tableA.column1 = tableB.column2;
1.INNER JOIN
2.LEFT OUTER JOIN
3.RIGHT OUTER JOIN
4.FULL OUTER JOIN
JOIN查询须要先肯定主表,而后把另外一个表的数据“附加”到结果集上;
INNER JOIN是最经常使用的一种JOIN查询,它的语法是SELECT ... FROM <表1> INNER JOIN <表2> ON <条件...>;
JOIN查询仍然可使用WHERE条件和ORDER BY排序。
条件 | 表达式举例1 | 表达式举例2 | 说明 |
---|---|---|---|
使用=判断相等 | score = 80 | name = 'abc' | 字符串须要用单引号括起来 |
使用>判断大于 | score > 80 | name > 'abc' | 字符串比较根据ASCII码,中文字符比较根据数据库设置 |
使用>=判断大于或相等 | score >= 80 | name >= 'abc' | |
使用<判断小于 | score < 80 | name <= 'abc' | |
使用<=判断小于或相等 | score <= 80 | name <= 'abc' | |
使用<>判断不相等 | score <> 80 | name <> 'abc' | |
使用LIKE判断类似 | name LIKE 'ab%' | name LIKE '%bc%' | %表示任意字符,例如'ab%'将匹配'ab','abc','abcd' |