python操作mysql步骤:
创建connect连接
conn = connect(host='127.0.0.1', port=3306, user='root', password='123456', database='jing_dong', charset='utf8')
获得cursor对象
cursor = conn.cursor()
执行SQL语句
cursor.execute('select * from xxx')
关闭corser和conn连接
cursor.close()
conn.close()
from pymysql import connect
class JD(object):
def __init__(self):
# 创建connect连接
self.conn = connect(host='127.0.0.1', port=3306, user='root',\
password='123456', database='jing_dong', charset='utf8')
# 获得cursor对象
self.cursor = self.conn.cursor()
def __del__(self):
# 关闭corser对象
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 name FROM goods_cates'
self.execute_sql(sql)
def show_brand(self):
"""显示所有的商品的品牌分类"""
sql = 'SELECT name FROM goods_brand'
self.execute_sql(sql)
def add_brand(self):
"""添加一个商品分类"""
item_name = input('输入新商品分类的名称: ')
sql = """INSERT INTO goods_cates(name) VALUES ('%s')""" % item_name
self.cursor.execute(sql)
self.conn.commit()
@staticmethod
def print_menu():
print('-----京东-----')
print('1.所有的商品')
print('2.所有的商品的分类')
print('3.所有的商品的品牌分类')
print('4.添加一个商品分类')
return input('请输入功能对应的序号: ')
def run(self):
while True:
op = self.print_menu()
if op == '1':
# 查询所有商品
self.show_all_item()
elif op == '2':
# 查询所有的商品的分类
self.show_cates()
elif op == '3':
# 查询所有的商品的品牌分类
self.show_brand()
elif op == '4':
# 添加一个商品分类
self.add_brand()
else:
print('输入有误,请重新输入...')
def main():
# 1.创建一个JD对象
jd = JD()
# 2.调用JD对象的run方法
jd.run()
if __name__ == '__main__':
main()