python與資料庫互動
原理:
db_config =
使用步驟:
1:匯入模組:import pymysql
2:建立連線:pymysql.connect(**dbconfig)
連線是不能運算元據庫的,需要用連線生成游標來操作
3:建立游標: connection.cursor()
4:執行sql語句:cursor. execute(sq.)
5:獲取結果:cur.fetchall()
eg:import pymysql
「」"a =
**afunc(**a)
func(name=『g1』, age=18) # 解包
pymysql這個庫實現了事務.
「」"
redis1:安裝python包redis: pip install redisdb_config =
conn = pymysql.connect(**db_config)
cur = conn.cursor() # create cursor.
try:
sq. = 'insert into students value (2, "jack")'
# sq. = 'select * from students'
rv = cur.execute(sq.) # execute, rv接收行數.
resp = cur.fetchall() # 接收展示內容.
[print(entry) for entry in resp]
except exception as e:
print(e)
conn.rollback() # 相當於撤銷, 如果失敗就回滾.
finally:
conn.commit() # 提交修改的資料.
cur.close() # 關閉游標.
conn.close() # 關閉conn.
2:連線redis:redis.strictredis()
3:在程式操作的資料為bytes型別,加入decode_responses=true,寫入的資料為str型別
eg:import redis
「」"10060
(你的電腦能夠ping到我們虛擬機器ip.)
1. 把虛擬機器的防火牆的6379開啟. sudo ufw allow 6379
2. redis服務的配置資訊.
sudo vim /etc/redis/redis.conf
bind 0.0.0.0
sudo /etc/init.d/redis-server restart
「」"
注:與在python使用的三個不同點red = redis.strictredis(host='192.168.75.250', port=6379, decode_responses=true)
print(red.keys())
red.set('name', 'jack')
print(red.type('name'))
# red.delete('name')
print(red.get('name'))
print(red.exists('name'))
red.mset()
print(red.mget('mname1', 'mname2'))
print(red.expire('name', 10))
print(red.ttl('name'))
print(red.set('exname', 'haha', 20))
print(red.ttl('exname'))
red.rename('exname', 'new_ex_name')
print(red.keys())
red.delete('list_name')
red.lpush('list_name', 'g1', 'g2', 'g3')
red.rpush('list_name', 'g4', 'g5', 'g6')
red.lrem('list_name', 0, 'g1')
print(red.lrange('list_name', 0, -1))
red.hset('hash_name', 'name', 'jack')
print(red.hget('hash_name', 'name'))
red.hmset('hash_name', )
print(red.hmget('hash_name', 'name', 'name1', 'name2'))
print(red.hgetall('hash_name'))
red.sadd('set_name', 1, 2, 3, 1, 2)
print(red.smembers('set_name'))
red.zadd('zset_name', 10, 'g1', 20, 'g2', 30, 'g3', 40, 'g3')
print(red.zrange('zset_name', 0, -1))
print(red.flushdb())
delete
mset
hmset
資料庫與python的互動
try from mysql import con connect host localhost port 3306,database df user root password mysql charset utf 8 2 連線物件 獲得cursor物件 cs1 con.cursor 執行inser...
python與資料庫mysql互動
通過pycharm簡潔 塊操作mysql,以幫助我們理解 具體步驟可分為五步 1,安裝並pymysql庫 pip install pymysql匯入pymysql庫 import pymysql2與資料庫建立鏈結,這裡用乙個字典來接收 db conf 3,建立游標物件 conn pymysql.co...
python和資料庫互動
對於關係型資料庫的訪問,python社群已經指定了乙個標準,稱為python database api sepcificationv2.0.mysql qracle等特定資料庫模組遵從這一規範,而且可新增更多特性,高階資料庫api定義了一組用於連線資料庫伺服器 執行sql語句並獲得結果的函式和物件,...