Python3中连接Mysql数据库进行查询、增加、删除数据

用python连接mysql数据库进行常用操作,将常用操作封装成了一个类方便调用

"""
连接数据库,查询、增加、删除数据
"""

import MySQLdb

class MysqlSearch(object):
	"""docstring for ClassName"""
	def __init__(self):
		# super(ClassName, self).__init__()
		# self.arg = arg
		self.get_conn()

	def get_conn(self):
		# 获取连接
		try:
			self.conn = MySQLdb.connect(
				host = 'localhost',
				user = 'root',
				passwd = 'root',
				db = 'data',
				port = 3306,
				charset = 'utf8'
			)
		except MySQLdb.Error as e:
			print('Error is: %s' % e)

	def close_conn(self):
		try:
			if self.conn:
				# 关闭连接
				self.conn.close()
		except MySQLdb.Error as e:
			print('Error is: %s' % e)

	def get_one(self):
		# 准备SQL
		sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;'
		# 找到cursor
		cursor = self.conn.cursor()
		# 执行SQL
		cursor.execute(sql,('百家',))   # 参数为元组,当只有一个元素时后面要加,
		# print(cursor.rowcount) # 打印行数
		# print(dir(cursor))   # 查看cursor属性
		# print(cursor.description)
		# 拿到结果
		rest = cursor.fetchone()
		rest = dict(zip([k[0] for k in cursor.description],rest))
		# print(rest)
		# print(rest['title'])
		# 处理数据
		# 关闭cursor、连接
		cursor.close()
		self.close_conn()
		return rest

	def get_more(self):
		# 准备SQL
		sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;'
		# 找到cursor
		cursor = self.conn.cursor()
		# 执行SQL
		cursor.execute(sql,('百家',))
		# print(cursor.rowcount) # 打印行数
		# print(dir(cursor))   # 查看cursor属性
		# print(cursor.description)
		# 拿到结果
		rest = cursor.fetchall()
		rest = [dict(zip([k[0] for k in cursor.description],row)) 
									for row in rest]
		# print(rest)
		# print(rest['title'])
		# 处理数据
		# 关闭cursor、连接
		cursor.close()
		self.close_conn()
		return rest

	def get_more2(self,page,page_size):
		offset = (page - 1) * page_size
		# 准备SQL
		sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC LIMIT %s %s;"
		# 找到cursor
		cursor = self.conn.cursor()
		# 执行SQL
		cursor.execute(sql,('百家',))
		# print(cursor.rowcount) # 打印行数
		# print(dir(cursor))   # 查看cursor属性
		# print(cursor.description)
		# 拿到结果
		rest = cursor.fetchall()
		rest = [dict(zip([k[0] for k in cursor.description],row)) 
									for row in rest]
		# print(rest)
		# print(rest['title'])
		# 处理数据
		# 关闭cursor、连接
		cursor.close()
		self.close_conn()
		return rest

	def add_one(self):
		try:
			# 准备SQL
			sql = (
					"INSERT INTO `news` (`title`,`content`,`types`) VALUE"
					"(%s,%s,%s);"
				  )  # 内容加单引号"
			# 找到cursor
			cursor = self.conn.cursor()
			# 执行SQL
			cursor.execute(sql,('标题15','陈军的测试10','最新',))
			cursor.execute(sql,('标题16','陈军的测试11','头条',))
			# 提交事务
			self.conn.commit()
			# 关闭cursor、连接
			cursor.close()
					
		except MySQLdb.Error as e:
			print("error is %s"%e)
			# self.conn.commit() # 提交多条数据,如果想让正常的存入,则再次提交即可
			self.conn.rollback() # 如果一条错误,本次提交全部失效
		self.close_conn()

	def delete_one(self):
		try:
			# 准备SQL
			# sql = (
			# 		"INSERT INTO `news` (`title`,`content`,`types`) VALUE"
			# 		"(%s,%s,%s);"
			# 	  )  # 内容加单引号"
			sql2 = ("DELETE FROM `table` WHERE id = 3")
			# 找到cursor
			cursor = self.conn.cursor()
			# 执行SQL
			# cursor.execute(sql,('标题15','陈军的测试10','最新',))
			# cursor.execute(sql,('标题16','陈军的测试11','头条',))
			cursor.execute(sql2)
			# 提交事务
			self.conn.commit()
			# 关闭cursor、连接
			cursor.close()
					
		except MySQLdb.Error as e:
			print("error is %s"%e)
			# self.conn.commit() # 提交多条数据,如果想让正常的存入,则再次提交即可
			self.conn.rollback() # 如果一条错误,本次提交全部失效
		self.close_conn()

	def test(self):
		try:
			# 准备SQL
			sql = (
					"INSERT INTO `news` (`title`,`content`,`types`) VALUE"
					"(%s,%s,%s);"
				  )  # 内容加单引号"
			# 找到cursor
			cursor = self.conn.cursor()
			# 执行SQL
			# cursor.execute(sql,('标题15','陈军的测试10','最新',))
			# cursor.execute(sql,('标题16','陈军的测试11','头条',))
			cursor.execute(sql)
			# 提交事务
			self.conn.commit()
			# 关闭cursor、连接
			cursor.close()
					
		except MySQLdb.Error as e:
			print("error is %s"%e)
			# self.conn.commit() # 提交多条数据,如果想让正常的存入,则再次提交即可
			self.conn.rollback() # 如果一条错误,本次提交全部失效
		self.close_conn()
		
def main():
	obj = MysqlSearch()
	# rest = obj.get_one()
	# print(rest["title"])

	# rest = obj.get_more()
	# for item in rest:
	# 	print(item["title"])
	# 	print("---"*10)
	obj.test()

if __name__ == '__main__':
	main()

猜你喜欢

转载自blog.csdn.net/qq_37273544/article/details/85234207
今日推荐