通过Python对mysql数据进行操作

六月ゝ 毕业季﹏ 提交于 2019-12-05 10:55:57

准备工作

  1. Ubuntu安装mysql服务器:sudo apt-get install mysql-server
  2. Ubuntu安装mysql客户端:sudo apt-get install mysql-client;并记住登录密码。
  3. Python安装pymysql用于通过Python操作mysql数据库:pip3 install pymysql
  4. 建立数据库,并建立相关联的三张表,博主建立的数据库名称为test,建立相关联表分别为:goods,good_cates,good_brands,效果如下图所示,且博主对数据库操作的例子均基于此。(数据基本操作请自行百度或参考其他博主)在这里插入图片描述

基本函数简介

1.con = connect(host=“localhost(本机ip)”, port=3306(端口,mysql默认端口即为3306), user=‘root’(用户名root), password=‘12345678’(博主设置的登录密码为12345678),database=‘test’(使用test数据库,注:使用前需事先建立数据库),charset=‘utf8’(采用utf-8编码方式))
2. con.cursor() #获取游标对象
3. con.cursor.execute(sql) #执行sql语句
4. connect连接对象和cursor对象使用完最后需用close关闭。

实例

  1. 建立Test对象,为其定义属性并写相应的方法
class Test(object):
	def __init__(self):
		#获取连接对象
		self.con = pymysql.connect(host="localhost", port=3306, user='root', password='12345678',database='test', charset='utf8')
		#获取游标对象
		self.cursor = self.con.cursor()

	def __del__(self):
		#关闭对象
		self.cursor.close()
		self.con.close()

	def execute_sql(self, sql):
		#执行sql语句
		self.cursor.execute(sql)
		for temp in self.cursor.fetchall():
			print(temp)
		
	@staticmethod
	def show_menu():
		print("----Test----")
		print("1:所有商品")
		print("2:所有商品分类")
		print("3:所有品牌分类")
		num = input("请输入功能对应的序号:")
		return num

	def run(self):
		while True:
			num = self.show_menu()
			print(num)
			if num == '1':
				#查询所有商品
				sql = "select * from goods;"
				self.execute_sql(sql)

			elif num == '2':
				#查询分类
				sql = "select name from good_cates;"
				self.execute_sql(sql)
				
			elif num == '3':
				#查询品牌
				sql = "select name from good_brands;"
				self.execute_sql(sql)
				
			else:
				print("无效字符!")
  1. 主函数调用
def main():
	#实例化对象
	test = Test()
	#调用对象run方法
	test.run()
if __name__ == "__main__":
	main()

  1. 效果演示
    在这里插入图片描述
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!