【python练习】python与mysql交互示例

今天进行了python与mysql交互,可以实现使用python操作SQL语言而得出想要的查询结果,练习代码如下:


from pymysql import *

class JD(object):

	def __init__(self):
		#创建Connection连接
		self.conn = connect(host='192.168.190.130',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
		#conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')

		#获取cursor对象
		self.cursor = self.conn.cursor()
		

	def __del__(self):
		self.cursor.close()
		self.conn.close()

	def execute_sql(self,sql):
		self.cursor.execute(sql)
		for temp in self.cursor.fetchall():
			print(temp)

	def show_all_item(self):
		"""显示所有商品"""
		sql = "select * from goods;"
		self.execute_sql(sql)

	def show_cates(self):
		""""""
		sql = "select * from goods_cates;"
		self.execute_sql(sql)

	def show_brands(self):
		""""""
		sql = "select * from goods_brands;"
		self.execute_sql(sql)

	def print_menu(self):
		print("---------------JD------------------")
		print("1:所有的商品!")
		print("2:所有的商品分类!")
		print("3:所有的商品品牌分类!")
		return input("请输入功能对应的序号:")

	def run(self):

		while True:
			num = self.print_menu()
			if num == "1":
				self.show_all_item()
			elif num =="2":
				self.show_cates()
			elif num =="3":
				self.show_brands()
			else:
				print("输入有误,请重新输入")
			

def main():

	#1、创建一个JD对象
	jd = JD()

	#2、调用对象run方法
	jd.run()


if __name__ == "__main__":
	main()

 

本人练习是win10的python环境,数据库用的是虚拟机的mysql。由于mysql限定了访问,网上咨询了方法,可以从配置win10的IP地址可以远程访问linux的mysql服务,详细转自下面大神博客,感谢:

https://blog.csdn.net/github_37216944/article/details/79270024

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值