pip install pymysql
#使用清华镜像源
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pymysql
PHPStudy是一个windows下的Apache/Ngnix+PHP+MySQL的集成开发环境
数据库单例测试
import pymysql
class MySqlSingleton:
isConnect = False
__db = None
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super(MySqlSingleton, cls).__new__(cls)
return cls._instance
#MySql数据库单例类设计
def __init__(self,host,user,passwd,db):
if MySqlSingleton.isConnect is False:
try:
self.__db = pymysql.connect(host=host, user=user, password=passwd, database=db)
print("数据库连接成功")
MySqlSingleton.isConnect = True
#创建游标
self.__cursor = self.__db.cursor()
except:
print('数据库连接失败')
def mysql_execute(self,sql):
try:
print("执行SQL成功")
self.__cursor.execute(sql)
# 提交到数据库执行
self.__db.commit()
except:
print("执行SQL失败")
# 如果发生错误则回滚
self.__db.rollback()
def mysql_select(self,sql):
try:
print("执行SQL查询数据成功")
self.__cursor.execute(sql)
# 提交到数据库执行
self.__db.commit()
#返回查询数据
#获取所有记录列表
data = self.__cursor.fetchall()
return data
except:
print("执行SQL查询数据失败")
# 如果发生错误则回滚
self.__db.rollback()
def __del__(self):
#关闭数据库
self.__db.close()
if __name__ == "__main__":
mydb = MySqlSingleton("localhost","admin","123456","wastedb")
# 如果表存在则删除
mydb.mysql_execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用预处理语句创建表
createsql = """CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
mydb.mysql_execute(createsql)
# SQL 插入语句
insertsql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
mydb.mysql_execute(insertsql)