我是靠谱客的博主 辛勤白猫,这篇文章主要介绍python操作sql_笔记:Python操作sql,现在分享给大家,希望可以做个参考。

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()

操作SQL修改数据库时commit()方法进行提交,如果在执行commit()方法前反悔,可以执行rollback()方法进行回退。

最后

以上就是辛勤白猫最近收集整理的关于python操作sql_笔记:Python操作sql的全部内容,更多相关python操作sql_笔记内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部