当前位置: 首页 > article >正文

搞定python之八----操作mysql

本文是《搞定python》系列文章的第八篇,讲述利用python操作mysql数据库。相对来说,本文的综合性比较强,包含了操作数据库、异常处理、元组等内容,需要结合前面的知识点。

1、安装mysql模块

PyMySql模块相当于数据库的驱动,我们在用java时也是要先下载驱动的,同样的道理。

pip3 install PyMySql

在这里插入图片描述

2、数据库准备

--创建数据库
create database my_test_db_01

-- 创建表
CREATE TABLE `shoping_00` (
  `shoping_id` bigint NOT NULL COMMENT '商品id',
  `shoping_name` varchar(255) DEFAULT NULL COMMENT '商品名称',
  `shoping_price` int NOT NULL COMMENT '商品价格',
  PRIMARY KEY (`shoping_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 ROW_FORMAT=COMPACT;

3、python代码

其实过程和jdbc非常相似,不多说了,看代码。

import pymysql   #引入类库

conn = None
cursor = None
result = None
try:
	# conn就是连接
    conn = pymysql.connect(host="192.168.99.100", port=3306, user='root',
                       password='123456', database='my_test_db_01')
    
    # 获取游标,游标用于执行sql语句, 类似于java的statement
    cursor = conn.cursor()
    cursor.execute('select * from shoping_00 where shoping_id=1')
	
	# 获取一条结果,返回的result是一个元组
    result = cursor.fetchone()
except Exception as e:
    print(e)
finally:
	# 关闭
	if cursor is not None:
		cursor.close()
    if conn is not None:
    	conn.close()

print("type(result): %s \n" % type(result))
print("shoping_id %s | shoping_name %s shoping_price %s"  %( result[0],result[1],result[2]))

4、事务处理

下段代码就是加上了事务提交和回滚,基本思路和jdbc思路相同。

import pymysql
import random

conn = None
cursor = None
result = None
try:
    conn = pymysql.connect(host="192.168.99.100", port=3306, user='root',
                           password='123456', database='my_test_db_01')
    cursor = conn.cursor()
    cursor.execute('select * from shoping_00 where shoping_id=1')
    result1 = cursor.fetchone()

	# 利用随机数,随机设置一个价格,便于看到效果
    cursor.execute('update shoping_00 set shoping_price=%d where shoping_id=1' %(random.randint(1, 99999)))
    
    cursor.execute('select * from shoping_00 where shoping_id=1')
    result2 = cursor.fetchone()
    
    # 事务提交
    conn.commit()
except Exception as e:
    print(e)
    
    # 事务回滚
    if conn is not None:
        conn.rollback()
finally:
    if cursor is not None:
        cursor.close()
    if conn is not None:
        conn.close()

print("-"*4 + "result1:" + "-"*4)
print("type(result): %s " % type(result1))
print("shoping_id %s | shoping_name %s | shoping_price %s" % (result1[0], result1[1], result1[2]))

print("\n" + "-"*4 + "result2:" + "-"*4)
print("shoping_id %s | shoping_name %s | shoping_price %s" % (result2[0], result2[1], result2[2]))

好了,本节就到这里了。
//~~


http://www.kler.cn/a/590502.html

相关文章:

  • 【SpringMVC】常用注解:@SessionAttributes
  • Qt QML解决SVG图片显示模糊的问题
  • @RequestBody注解解释
  • 服务创造未来 东隆科技携多款产品亮相慕尼黑
  • 【网络协议】基于UDP的可靠协议:KCP
  • Git 使用指南
  • 【多线程】单例模式
  • Unity学习之Shader总结(一)
  • Docker入门篇2:查看容器、运行容器、启动和停止容器、删除容器
  • Android PC 要来了?Android 16 Beta3 出现 Enable desktop experience features 选项
  • 【STM32】NVIC(嵌套向量中断控制器)
  • Android之RecyclerView列表拖动排序
  • Vue3项目白屏问题深度解析:从AI辅助诊断到性能优化实战
  • 《灵珠觉醒:从零到算法金仙的C++修炼》卷三·天劫试炼(49)万鸦壶焚网络 - 网络延迟时间(Bellman-Ford)
  • Spring boot+mybatis的批量删除
  • 【AI】深度学习与人工智能应用案例详解
  • LIMS系统在纸制品制造的应用 内检实验室LIMS系统提升纸制品质控
  • Postman发送GET请求示例及注意事项
  • Vue.js 事件处理与修饰符详解
  • 2. qt写带有槽的登录界面(c++)