Python:mysql-connector-Python模塊對MySQL數(shù)據(jù)庫進行增刪改查
Mysql文檔:https://dev.Mysql.com/doc/connector-python/en/

PYPI: https://pypi.org/project/mysql-connector-python/
mysql-connector-python 是MySQL官方的Python語言MySQL連接模塊
安裝
$ pip install mysql-connector-python
1
代碼示例
連接管理
# -*- coding: utf-8 -*- import mysql.connector db_config = { "database": "mydata", "user": "root", "password": "123456", "host": "127.0.0.1", "port": 3306, } # 連接數(shù)據(jù)庫獲取游標,可以設(shè)置返回數(shù)據(jù)的格式,元組,命令元組,字典等... connect = mysql.connector.Connect(**db_config) cursor = connect.cursor(dictionary=True) # 關(guān)閉游標和連接 cursor.close() connect.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
寫操作
數(shù)據(jù) 寫入 和 更新 都可以使用 execute 和 executemany
刪除就使用execute
寫操作都需要 commit 才會生效
# 插入元組數(shù)據(jù) insert_tuple_sql = "insert into student(name, age) values(%s, %s)" data = ("Tom", 23) cursor.execute(insert_tuple_sql, data) connect.commit() print(cursor.lastrowid) # 一般插入一條時使用,獲取插入id # 插入多條元組數(shù)據(jù) insert_tuple_sql = "insert into student(name, age) values(%s, %s)" data = [ ("Tom", 23), ("Jack", 25), ] cursor.executemany(insert_tuple_sql, data) connect.commit() # 插入字典數(shù)據(jù) insert_dict_sql = "insert into student(name, age) values(%(name)s, %(age)s)" data = { "name": "Tom", "age": 25 } cursor.execute(insert_dict_sql, data) connect.commit() # 插入多條字典數(shù)據(jù) insert_dict_sql = "insert into student(name, age) values(%(name)s, %(age)s)" data = [ { "name": "Tom", "age": 26 }, { "name": "Jack", "age": 27 } ] cursor.executemany(insert_dict_sql, data) connect.commit()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
讀操作
cursor.execute("select * from student where name=%s limit 3", ("Tom",)) rows = cursor.fetchall() print(rows) # 因為開始設(shè)置的返回數(shù)據(jù)格式是字典 dictionary ,所以直接返回字典數(shù)據(jù) # [ # {'id': 1, 'name': 'Tom', 'age': 23}, # {'id': 2, 'name': 'Tom', 'age': 23}, # {'id': 3, 'name': 'Tom', 'age': 25} #] # 獲取一些元數(shù)據(jù)信息 print(cursor.column_names) # ('id', 'name', 'age') print(cursor.description) # [ # ('id', 3, None, None, None, None, 0, 16899), # ('name', 253, None, None, None, None, 1, 0), # ('age', 3, None, None, None, None, 1, 0) #] print(cursor.rowcount) # 3 print(cursor.statement) # select * from student where name='Tom' limit 3 print(cursor.with_rows) # True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
MySQL Python 數(shù)據(jù)庫
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。