Python學習:操作資料庫
阿新 • • 發佈:2020-12-29
技術標籤:Pythonmysqlpythonsqljava資料庫
Python學習:操作資料庫
安裝 PyMySQL:
pip3 install PyMySQL
查詢資料
import pymysql
'''
資料庫使用者名稱: root
密碼: 123456
資料庫名: pysql
資料庫表名: table1
'''
# 開啟資料庫連線
db = pymysql.connect("localhost", "root", "123456", "pysql")
# 使用cursor()方法獲取操作遊標
cursor = db.cursor()
# SQL 查詢語句
sql = "SELECT * FROM table1"
try:
# 執行SQL語句
cursor.execute(sql)
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
address = row[2]
print("id=",id," name=",name," address=" ,address)
except:
print("Error: unable to fetch data")
# 關閉資料庫連線
db.close()
新增資料
import pymysql
'''
資料庫使用者名稱: root
密碼: 123456
資料庫名: pysql
資料庫表名: table1
'''
# 開啟資料庫連線
db = pymysql.connect("localhost", "root", "123456", "pysql")
# 使用cursor()方法獲取操作遊標
cursor = db.cursor()
# SQL 插入語句
sql = """INSERT INTO table1 (id,name,address) VALUES ('5', 'Mohan', '北京')"""
try:
# 執行sql語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()
except:
# 如果發生錯誤則回滾
db.rollback()
# 關閉資料庫連線
db.close()
刪除資料
import pymysql
'''
資料庫使用者名稱: root
密碼: 123456
資料庫名: pysql
資料庫表名: table1
'''
# 開啟資料庫連線
db = pymysql.connect("localhost", "root", "123456", "pysql")
# 使用cursor()方法獲取操作遊標
cursor = db.cursor()
# SQL 刪除語句
sql = "DELETE FROM table1 WHERE id = %s" % (3)
try:
# 執行SQL語句
cursor.execute(sql)
# 提交修改
db.commit()
except:
# 發生錯誤時回滾
db.rollback()
# 關閉連線
db.close()
更新資料
import pymysql
'''
資料庫使用者名稱: root
密碼: 123456
資料庫名: pysql
資料庫表名: table1
'''
# 開啟資料庫連線
db = pymysql.connect("localhost", "root", "123456", "pysql")
# 使用cursor()方法獲取操作遊標
cursor = db.cursor()
# SQL 更新語句
sql = "UPDATE table1 SET address = '%s' WHERE name = '%s'" % ('非洲','Mohan')
try:
# 執行SQL語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()
except:
# 發生錯誤時回滾
db.rollback()
# 關閉資料庫連線
db.close()