pymysql
安装pymysql
使用 pymysql
import pymysql
from functools import wraps
# 四个参数(连接地址,登录数据库用户,数据连接密码,数据库名字)
db = pymysql.connect('localhost', 'root', 'mysql', 'books')
c = db.cursor() # 获取游标cursor
## 查询所有表
sql = 'show tables;'
c.execute(sql) # 执行sql语句
query = c.fetchall()
# fetch 取,获取 all 全部
# print(query)
## 查询books表里的所有记录
sql = 'select * from books'
c.execute(sql)
query = c.fetchall()
# print(query)
# CURD
# sql = '''
# insert into books(book_name,author,publish,prints,publish_date)values
# ('三国演义','罗贯中','中州古籍出版社',100,'2019-04-01');
# '''
# c.execute(sql)
# db.commit() # 提交
# query=c.fetchall()
# print(query)
sql = 'select * from books'
c.execute(sql)
query = c.fetchall()
# print(query)
# # pymysql 删除数据
# sql ='delete from books where id=4'
# try:
# c.execute(sql)
# db.commit() # 只要涉及到数据变更的,一定要带上 commit
# except:
# db.rollback()
#
# pymysql 修改数据
# sql='update books set author="四毛" where id=1'
#
# try:
# c.execute(sql)
# db.commit()
# except:
# db.rollback()
# sql='select * from books'
# # [{},{},{}]
# try:
# c.execute(sql)
# query =c.fetchall()
# res =[]
# for x in query:
# temp ={}
# temp['book_name']=x[1]
# temp['author']=x[2]
# res.append(temp)
# except:
# print('查询错误')
#
# print(res)
# c.close()
# db.close()
'''
定义单例装饰器
'''
def singleton(cls):
_instance ={} # 定义集合放置cls的实例
@wraps(cls)
def getInstance(*args,**kwargs):
if cls not in _instance: # 如果没有实例,则生成一个
_instance[cls]=cls(*args,**kwargs)
return _instance[cls] # 返回实例
return getInstance
@singleton
class pysql(object):
def __init__(self):
print('class instance1')
p1 = pysql()
p2 = pysql()
print(id(p1))
print(id(p2))