環境配置
Python是出了名的友善,但是在mac下搭建python通路 mysql 資料庫的環境時還真碰到不少問題。
mysql 安裝
mysql 安裝簡單需要注意:
連接配接MySQL出現報錯client does not support authentication protocol requested by server consider
執行以下代碼
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
其中password需要改成你自己的密碼,大概原因是MySQL8.0的加密方式改變了,但是比較老版本的navicate沒有來得及支援,是以需要将mysql設定為支援傳統的那種密碼加密,如果用比較低版本的MySQL,比如MySQL57應該就不會出現這種問題。
FLUSH PRIVILEGES;
pymysql 子產品安裝
sudo pip install pymysql
sudo pip install MySQLdb
代碼編寫
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import pymysql
# 打開資料庫連接配接
db = pymysql.connect("127.0.0.1", "root", "password", "python_statistics", charset='utf8')
#使用cursor()方法擷取操作遊标
cursor=db.cursor()
#使用execute方法執行SQL語句
cursor.execute("select * from phone_communication_order limit 10")
#使用 fetchone 方法擷取一條資料
data = cursor.fetchone()
#輸出查詢結果
print(data)
#關閉資料源
db.close()

image.png
建表語句
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `phone_communication_order`
-- ----------------------------
DROP TABLE IF EXISTS `phone_communication_order`;
CREATE TABLE `phone_communication_order` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`dial_date` datetime NOT NULL,
`dial_channel` varchar(255) DEFAULT NULL,
`phone_num` varchar(255) DEFAULT NULL,
`phone_bind_num` int(11) DEFAULT NULL,
`efficacious_communicate` varchar(255) DEFAULT NULL,
`communication_landlord` int(11) DEFAULT NULL,
`order_count_7` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48080 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SET FOREIGN_KEY_CHECKS = 1;