python使用mysql数据库

环境配置

  1. python+pymsql
  2. mysql

mysql的常用操作

https://www.jianshu.com/p/d9d7d54ec023

python调用mysql

构建数据库连接

1
2
3
4
5
6
import pymysql

def getdb():
global db
db = pymysql.connect("localhost", "root", "123", "attendance_check") # 打开数据库连接
return db

通过数据库连接执行sql语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
db = sqldb.getdb()
cursor = db.cursor()
# SQL 插入语句
sql = """(sql语句)"""
try:
cursor.execute(sql) # 执行sql语句
db.commit() # 提交到数据库执行
db.close()
# print("success")
return True
except:
db.rollback() # 如果发生错误则回滚
db.close()
# print("error")
return False
# 关闭数据库连接
坚持原创技术分享,您的支持也将成为我的动力!
-------------本文结束感谢您的阅读-------------
undefined