python数据库教程_Python连接mysql数据库及简单增删改查操作示例代码
1.安裝pymysql
進(jìn)入cmd,輸入 pip install pymysql:
2.數(shù)據(jù)庫(kù)建表
在數(shù)據(jù)庫(kù)中,建立一個(gè)簡(jiǎn)單的表,如圖:
3.簡(jiǎn)單操作
3.1查詢(xún)操作
#coding=utf-8
#連接數(shù)據(jù)庫(kù)測(cè)試
import pymysql
#打開(kāi)數(shù)據(jù)庫(kù)
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
#使用cursor()方法獲取操作游標(biāo)
cur = db.cursor()
#查詢(xún)操作
sql = "select * from books"
try:
# 執(zhí)行sql語(yǔ)句
cur.execute(sql)
results = cur.fetchall()
#遍歷結(jié)果
for rows in results:
id = rows[0]
name = rows[1]
price = rows[2]
bookcount = rows[3]
author = rows[4]
print("id: {}, name: {}, price: {}, bookcount: {}, author: {}".format(id,name,price,bookcount,author))
except Exception as e:
raise e
finally:
db.close()
運(yùn)行結(jié)果:
3.2插入操作
#coding=utf-8
#插入操作
import pymysql
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
cur = db.cursor()
sql = """insert into books(id,bookname,price,bookCount,author) values (4,'三體',20,3,'劉慈欣')"""
try:
cur.execute(sql)
#提交
db.commit()
except Exception as e:
#錯(cuò)誤回滾
db.rollback()
finally:
db.close()
運(yùn)行結(jié)果:
3.3更新操作
#coding=utf-8
#更新操作
import pymysql
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
# 使用cursor()方法獲取游標(biāo)
cur = db.cursor()
sql_update = "update books set bookname = '%s',author = '%s' where id = %d"
try:
cur.execute(sql_update % ("邊城","沈從文",4))
#提交
db.commit()
except Exception as e:
#錯(cuò)誤回滾
db.rollback()
finally:
db.close()
運(yùn)行結(jié)果:
3.4刪除操作
#coding=utf-8
#刪除操作
import pymysql
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
#使用cursor()獲取操作游標(biāo)
cur = db.cursor()
sql_delete = "delete from books where id = %d"
try:
#向sql語(yǔ)句傳遞參數(shù)
cur.execute(sql_delete % (1))
#提交
db.commit()
except Exception as e:
#錯(cuò)誤回滾
db.rollback()
finally:
db.close()
運(yùn)行結(jié)果:
到此這篇關(guān)于Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼的文章就介紹到這了,更多相關(guān)Python連接mysql數(shù)據(jù)庫(kù)及增刪改查操作內(nèi)容請(qǐng)搜索python博客以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持python博客!
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python数据库教程_Python连接mysql数据库及简单增删改查操作示例代码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 安装python应该先安装pycharm
- 下一篇: python数据库优化_Python学习