今天學習一下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' |