python3 MySQL数据库的常用操作

代码如下:

from myconn import myconn

class Sql:
	def __init__(self,db=None):
		# 初始化连接数据库
		# self.conn = pymysql.connect(db=dataName, user="user", passwd="passwd", host="host",charset='utf8')
		self.conn = myconn.get_conn(db) if db!=None else myconn.get_conn()

	def get_databases(self):
		""" 获取所有数据库名 """
		return self.getSqlData("show databases")
	def get_tables(self):
		""" 获取所有表名 """
		return self.getSqlData("show tables")


	def get_fields(self,table):
		""" 获取指定表的字段 """
		cur = self.conn.cursor()
		sql = "SELECT * FROM {} LIMIT 1".format(table)
		cur.execute(sql)
		v = cur.description
		zds = [i[0] for i in v]
		self.conn.commit()
		return zds


	def unique(self,table,*fields):
		""" 唯一设置 
		table:表名,fields:字段名列表; """
		cur = self.conn.cursor()
		if len(fields) == 1:
			sql = "ALTER TABLE {} ADD unique(".format(table)
		else:
			sql = "ALTER TABLE {} ADD UNIQUE KEY(".format(table)
		for i in fields:
			sql += i
			if i != fields[-1]:
				sql += ','
			else:
				sql += ')'
		try:
			cur.execute(sql)
		except Exception as exc:
			print(exc)
		else:
			self.conn.commit()

	def getSqlData(self, sql):
		''' 从数据库查询数据 '''
		cur = self.conn.cursor()
		cur.execute(sql)
		return cur.fetchall()
		
	def closeSql(self):
		self.conn.close()

猜你喜欢

转载自blog.csdn.net/a649344475/article/details/80896741