pip install pymysql
要操做數據庫,首先就要創建和數據庫的鏈接,配置pymysql.connect鏈接數據庫python
con = pymysql.connect(
host = '主機',
port = 端口,
user = '用戶名',
password = '密碼',
db = '數據庫名',
charset = 'utf8'
)
# 定義遊標
cursor = con.cursor()
cursor.execute('show databases') #執行sql
one = cursor.fetchone() #取出一條數據
all = cursor.fetchall() #取出全部數據
print(one)
print(all)
# 插入
row = cursor.execute("insert into test(name,sex) values(%s,%s)", ('佳能','男'))
# 更新
row = cursor.execute("update test set name= '張三' where id = %s", (2,))
# 刪除
cursor.execute('delete from user where id=%s ',(13,) )
# 關閉鏈接
con.commit() #提交事物
cursor.close() #關閉遊標
con.close() # 關閉鏈接
## 聯合查詢
union = '''
select s.name, c.name,d.name from `student` s
left join `select` se on se.s_id = s.s_id
left join course c on se.c_id = c.id
left join department d on s.dept_id = d.id
ORDER BY s.name;
'''
# cursor.execute(union)
# find =cursor.fetchall()
pip install redis
# 建立鏈接
re = redis.Redis(host='127.0.0.1', port='55555', password='qwe123')
## 測試
re.set('num',15)
print(re.get('num'))
## set 中文
re.set('name','張三')
print(re.get('name').decode('utf8') )
## 字符的 編碼
s = '佳能'.encode('utf8')
print(type(s),s)
s2 = s.decode()
print(type(s2),s2)
### 大部分的命令 和 redis 中操做同樣
不一樣:
re.ttl() ### 不能看 負數 -1 -2
re.mset() ## 用鍵值對
re.incr() ## incr 能夠加參數的,代替了 incrby
re.decr() ## decr 能夠加參數,代替了 decrby
re.lrem() ## num 放到後面
re.hmset() # 多插入,要用字典