36.1 连接数据库
MySQL Connector/Python
| Connector/Python | MySQL Server | Python |
|---|---|---|
| 8.0 | 8.0, 5.7, 5.6, 5.5 | 3.6, 3.5, 3.4, 2.7 |
| 2.2 | 5.7, 5.6, 5.5 | 3.5, 3.4, 2.7 |
| 2.1 | 5.7, 5.6, 5.5 | 3.5, 3.4, 2.7, 2.6 |
| 2.0 | 5.7, 5.6, 5.5 | 3.5, 3.4, 2.7, 2.6 |
| 1.2 | 5.7, 5.6, 5.5 (5.1, 5.0, 4.1) | 3.4, 3.3, 3.2, 3.1, 2.7, 2.6 |
pip install mysql-connector-python
pip install mysql-connector-python==8.0.28
pip uninstall mysql-connector-python
Proceed (y/n)? y
>>> import mysql.connector
>>> mysql.connector.connect(host='localhost',database='mysql',user='root',password='your pass')
<mysql.connector.connection.MySQLConnection object at 0x0187AE50>
使用 connect() 函数连接 MySQL
import mysql.connector
from mysql.connector import Error
def connect():
""" Connect to MySQL database """
conn = None
try:
conn = mysql.connector.connect(host='192.168.56.104',
database='hrdb',
user='tony',
password='tony')
if conn.is_connected():
print('Connected to MySQL database')
except Error as e:
print(e)
finally:
if conn is not None and conn.is_connected():
conn.close()
if __name__ == '__main__':
connect()
>python connect.py
Connected to MySQL database
1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
2003: Can't connect to MySQL server on 'localhost:3306' (10061 No connection could be made because the target machine actively refused it)
使用 MySQLConnection 对象连接 MySQL
[mysql]
host = 192.168.56.104
port = 3305
database = hrdb
user = tony
password = tony
from configparser import ConfigParser
def read_db_config(filename='config.ini', section='mysql'):
""" Read database configuration file and return a dictionary object
:param filename: name of the configuration file
:param section: section of database configuration
:return: a dictionary of database parameters
"""
# create parser and read ini configuration file
parser = ConfigParser()
parser.read(filename)
# get section, default to mysql
db = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception('{0} not found in the {1} file'.format(section, filename))
return db
>>> from python_mysql_dbconfig import read_db_config
>>> read_db_config()
{'host': '192.168.56.104', 'port': '3306', 'database': 'hrdb', 'user': 'tony', 'password': 'tony'}
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def connect():
""" Connect to MySQL database """
db_config = read_db_config()
conn = None
try:
print('Connecting to MySQL database...')
conn = MySQLConnection(**db_config)
if conn.is_connected():
print('Connection established.')
else:
print('Connection failed.')
except Error as error:
print(error)
finally:
if conn is not None and conn.is_connected():
conn.close()
print('Connection closed.')
if __name__ == '__main__':
connect()
>python connect2.py
Connecting to MySQL database...
connection established.
Connection closed.
36.2 查询数据
fetchone() 方法
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def query_with_fetchone():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM department")
row = cursor.fetchone()
while row is not None:
print(row)
row = cursor.fetchone()
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
query_with_fetchone()
fetchall() 方法
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def query_with_fetchall():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM department")
rows = cursor.fetchall()
print('Total Row(s):', cursor.rowcount)
for row in rows:
print(row)
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
query_with_fetchall()
fetchmany() 方法
def iter_row(cursor, size=10):
while True:
rows = cursor.fetchmany(size)
if not rows:
break
for row in rows:
yield row
def query_with_fetchmany():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM employee")
for row in iter_row(cursor, 10):
print(row)
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
36.3 插入数据
插入单行数据
-- 通过 SQL 脚本创建表
CREATE TABLE books(
id INTEGER NOT NULL AUTO_INCREMENT,
title VARCHAR(50) NOT NULL,
isbn VARCHAR(13) NOT NULL,
photo BLOB,
PRIMARY KEY (id)
);
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def insert_book(title, isbn):
query = "INSERT INTO books(title,isbn) " \
"VALUES(%s,%s)"
args = (title, isbn)
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.execute(query, args)
if cursor.lastrowid:
print('last insert id', cursor.lastrowid)
else:
print('last insert id not found')
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()
def main():
insert_book('SQL编程思想','9787121421402')
if __name__ == '__main__':
main()
插入多行数据
INSERT INTO books(title,isbn)
VALUES ('高性能MySQL(第4版)', '9787121442575'),
('Linux是怎样工作的', '9787115581617'),
('机器学习', '9787302423287');
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def insert_books(books):
query = "INSERT INTO books(title,isbn) " \
"VALUES(%s,%s)"
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.executemany(query, books)
conn.commit()
except Error as e:
print('Error:', e)
finally:
cursor.close()
conn.close()
def main():
books = [('高性能MySQL(第4版)', '9787121442575'),
('Linux是怎样工作的', '9787115581617'),
('深度学习', '9787302423287')]
insert_books(books)
if __name__ == '__main__':
main()
36.4 更新数据
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def update_book(book_id, title):
# read database configuration
db_config = read_db_config()
# prepare query and data
query = """ UPDATE books
SET title = %s
WHERE id = %s """
data = (title, book_id)
try:
conn = MySQLConnection(**db_config)
# update book title
cursor = conn.cursor()
cursor.execute(query, data)
# accept the changes
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
update_book(4, '机器学习')
UPDATE books
SET title = '机器学习'
WHERE id = 4
SELECT id, title, isbn
FROM books
WHERE id = 4;
id|title |isbn |
--+--------+-------------+
4|深度学习 |9787302423287|
python update.py
SELECT id, title, isbn
FROM books
WHERE id = 4;
id|title |isbn |
--+--------+-------------+
4|机器学习 |9787302423287|
36.5 删除数据
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def delete_book(book_id):
db_config = read_db_config()
query = "DELETE FROM books WHERE id = %s"
try:
# connect to the database server
conn = MySQLConnection(**db_config)
# execute the query
cursor = conn.cursor()
cursor.execute(query, (book_id,))
# accept the change
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
delete_book(4)
DELETE FROM books
WHERE id = 4;
36.6 调用存储过程
准备工作
USE hrdb;
DELIMITER $$
CREATE PROCEDURE find_all()
BEGIN
SELECT
title,
isbn
FROM books
ORDER BY title;
END$$
DELIMITER ;
CALL find_all();
title |isbn |
-------------------+-------------+
Linux是怎样工作的 |9787115581617|
SQL编程思想 |9787121421402|
高性能MySQL(第4版)|9787121442575|
DELIMITER $$
CREATE PROCEDURE find_by_isbn(
IN p_isbn VARCHAR(13),
OUT p_title VARCHAR(50)
)
BEGIN
SELECT title
INTO p_title
FROM books
WHERE isbn = p_isbn;
END$$
DELIMITER ;
CALL find_by_isbn('9787121421402',@title);
SELECT @title;
@title |
----------+
SQL编程思想|
Python 调用存储过程
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def call_find_all_sp():
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.callproc('find_all')
# print out the result
for result in cursor.stored_results():
print(result.fetchall())
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
call_find_all_sp()
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def call_find_by_isbn():
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
args = ['9787121421402', 0]
result_args = cursor.callproc('find_by_isbn', args)
print(result_args[1])
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
call_find_by_isbn()
36.7 读写 BLOB 对象
更新 BLOB 字段
def read_file(filename):
with open(filename, 'rb') as f:
photo = f.read()
return photo
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def update_blob(book_id, filename):
# read file
data = read_file(filename)
# prepare update query and data
query = "UPDATE books " \
"SET photo = %s " \
"WHERE id = %s"
args = (data, book_id)
db_config = read_db_config()
try:
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.execute(query, args)
conn.commit()
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
def main():
update_blob(1, "pictures\thinking_in_sql.png")
if __name__ == '__main__':
main()
读取 BLOB 字段
def write_file(data, filename):
with open(filename, 'wb') as f:
f.write(data)
def read_blob(book_id, filename):
query = "SELECT photo FROM books WHERE id = %s"
# read database configuration
db_config = read_db_config()
try:
# query blob data form the books table
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.execute(query, (book_id,))
photo = cursor.fetchone()[0]
# write blob data into a file
write_file(photo, filename)
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
def main():
read_blob(144,"output\thinking_in-sql.jpg")
if __name__ == '__main__':
main()
文章转载自SQL编程思想,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。






