mysql數據庫
版本:mysql Ver 8.0.12 for Win64 on x86_64 (MySQL Community Server - GPL)
0.免密登陸
mysql -u root -p
不輸密碼直接回車
1.創建表DB
、用戶scraper1
CREATE DATABASE DB;
創建用戶:
create user 'scraper1'@'localhost' identified by 'passwd'
授予其所有權限:
grant all privileges on DB.* to 'scraper1'@'localhost' with grant option;
2.創建表users
CREATE table 'users'(
'id' int(11) not null auto_increment
,
'email' varchar(255) collate utf8_bin not null,
'password' varchar(255) collate utf8_bin not null,
primary key('id')
)
engine=InnoDB default charset=utf8 collate=utf8_bin auto_increment=1;
通過pymysql
模塊對mysql
數據庫操作:
import pymysql.cursors
# 建立連接
connection = pymysql.connect(
host = 'localhost',
user = 'scraper1' ,
password = 'passwd' ,
db = 'DB' ,
charset = 'utf8mb4' ,
cursorclass = pymysql.cursors.DictCursor)
try :
with connection.cursor() as cursor : # 打開當前連接的cursor()
sql = "INSERT INTO `users` (`email`,`password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]','passwd')) # 通過當前cursor()執行sql語句
connection.commit() # commit
with connection.cursor() as cursor :
sql = "SELECT `id` , `password` FROM `users` WHERE `email` = %s"
cursor.execute(sql, ('[email protected]'))
result = cursor.fetchone() # 只取最上面的第一條結果,返回單個元組如('id','title')
print(result) # {'id': 1, 'password': 'passwd'}
except :
connection.rollback() # 回滾
finally:
connection.close() # 關閉連接