python操作数据库
1、python連接mysql
首先安裝pymysql? pip install PyMySQL
import pymysql.cursors
from datetime import datetime
# 連接數(shù)據(jù)庫
connect = pymysql.Connect(
host='localhost',
port=3306,
user='root',
passwd='',
db='guest',
charset='utf8'
)
# 獲取游標
cursor = connect.cursor()
# 插入數(shù)據(jù)
sql = "INSERT INTO sign_event VALUES (14,'小米發(fā)布會','地鐵站',100,100,'2016-08-20 00:25:42','2016-08-20 00:25:42');"
print(sql)
cursor.execute(sql)
connect.commit()
print('成功插入', cursor.rowcount, '條數(shù)據(jù)')
#修改數(shù)據(jù)
sql = "UPDATE sign_event SET name = '葫蘆娃' WHERE id = 14 "
cursor.execute(sql)
connect.commit()
print('成功修改', cursor.rowcount, '條數(shù)據(jù)')
# 查詢數(shù)據(jù)
sql = "SELECT name,status FROM sign_event WHERE id = 14 "
cursor.execute(sql)
for row in cursor.fetchall():
print("name:%s\status:%s" % row)
print('共查找出', cursor.rowcount, '條數(shù)據(jù)')
# 事務處理
sql_1 = "UPDATE sign_event SET `limit` = `limit` + 100 WHERE id = 14 "
sql_2 = "UPDATE sign_event SET `limit` = `limit` + 200 WHERE id = 14 "
sql_3 = "UPDATE sign_event SET `limit` = `limit` - 100 WHERE id = 14 "
try:
cursor.execute(sql_1)
cursor.execute(sql_2)
cursor.execute(sql_3)
except Exception as e:
connect.rollback() # 事務回滾
print('事務處理失敗', e)
else:
connect.commit() # 事務提交
print('事務處理成功', cursor.rowcount)
# 刪除數(shù)據(jù)
sql = "DELETE FROM sign_event WHERE id = 14"
cursor.execute(sql)
connect.commit()
print('成功刪除', cursor.rowcount, '條數(shù)據(jù)')
# 關閉連接
cursor.close()
connect.close()
轉(zhuǎn)載于:https://www.cnblogs.com/huluwahaha/p/8178043.html
總結
以上是生活随笔為你收集整理的python操作数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓手机能更改手机屏幕刷新频率吗?
- 下一篇: 三十七 Python分布式爬虫打造搜索