python基础之操作MySQL数据库

工作需要操作MySQL数据库,使用pymysql库,有些操作上不习惯的地方做了些修改。比如查询的时候结果不能按字段名读取数据等。以下是代码。

首先是引入库、引入random和string主要是为了生成id。

复制代码
import pymysql
import random
import string

创建数据库链接对象

复制代码
def mysqlconnect():
    # 连接数据库
    host = '192.168.1.1
    port = 3306
    user = 'root'
    password = 'root'
    database = 'ceshi_table'
    conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
    cursor = conn.cursor()
    return cursor,conn

一、查询方法

复制代码
def selectdata(sql_query):
    cursor,conn = mysqlconnect()

    # 执行SQL查询语句
    cursor.execute(sql_query)

    # 获取查询结果
    results = cursor.fetchall()

    # 查询
    column_names = [desc[0] for desc in cursor.description]
    data = []
    for row in results:
        name_value = {}
        for column_name in column_names:
            name_value[column_name] = row[column_names.index(column_name)]
        data.append(name_value)

    # 关闭游标和连接
    cursor.close()
    conn.close()

    if len(data) == 1:
        return data[0]
    else:
        return data

调用

复制代码
sql_query = "SELECT * FROM data_table"
results = selectdata(sql_query)
print(results)

二、添加数据方法

复制代码
def insertdata(insertsql,values):
    cursor,conn = mysqlconnect()
    try:
        if type(values) == list:
            cursor.executemany(insertsql, values)

        if type(values) == tuple:
            cursor.execute(insertsql, values)

        conn.commit()
    except Exception as e:
        print(f"数据插入失败:{e}")
        conn.rollback()

    # 关闭游标和连接
    cursor.close()
    conn.close()

调用

复制代码
insertsql = "insert into data_table (id,warning_type,customer,license,tel) values (%s,%s,%s,%s,%s)"
values = [('123133', '123123','城区据','第一市场队'),
('123125', '123123','城区据','第一市场队'),
('123178', '123123','城区据','第一市场队')]
# values = ('123127', '123123','城区据','第一市场队')
insertdata(insertsql,values)

三、更新数据方法

复制代码
def updatedata(update_sql,values):
    cursor,conn = mysqlconnect()
    try:
        cursor.execute(update_sql, values)
        conn.commit()
    except Exception as e:
        print(f"数据更新失败:{e}")
        conn.rollback()

    # 关闭游标和连接
    cursor.close()
    conn.close()

调用

复制代码
update_sql = "UPDATE data_table SET area_name=%s,squadron_code=%s WHERE id=%s"
values = ('new_value1', 'condition_value','123123')
updatedata(update_sql,values)

四、删除数据方法

复制代码
def deledata(delete_sql,delevalue):
    cursor, conn = mysqlconnect()
    try:
        cursor.execute(delete_sql, delevalue)
        conn.commit()
    except Exception as e:
        print(f"数据删除失败:{e}")
        conn.rollback()

    # 关闭游标和连接
    cursor.close()
    conn.close()

调用

复制代码
delete_sql = "DELETE FROM data_table WHERE id=%s"
values = ('123123')
deledata(delete_sql,values)

五、最后还有个生成随机字符串id的方法

复制代码
def generate_random_string(length):
    characters = string.ascii_letters + string.digits  # 包含所有大小写字母和数字
    random_string = ''.join(random.choice(characters) for _ in range(length))
    return random_string

ok,完毕!!

相关推荐
计算机毕业编程指导师5 分钟前
【计算机毕设选题】基于Spark的车辆排放分析:2026年热门大数据项目 毕业设计 选题推荐 毕设选题 数据分析 机器学习 数据挖掘
大数据·hadoop·python·计算机·spark·毕业设计·车辆排放
浔川python社10 分钟前
浔川社团关于产品数据情况的官方通告
python
生活很暖很治愈12 分钟前
GUI自动化测试[3]——控件&数鼠标操作
windows·python·功能测试·测试工具
老蒋每日coding23 分钟前
Python3基础练习题详解,从入门到熟练的 50 个实例(一)
开发语言·python
HAPPY酷29 分钟前
构建即自由:一份为创造者设计的 Windows C++ 自动化构建指南
开发语言·c++·ide·windows·python·策略模式·visual studio
瑶池酒剑仙31 分钟前
Libvio.link爬虫技术解析大纲
爬虫·python
喵手37 分钟前
Python爬虫实战:构建 Steam 游戏数据库:requests+lxml 实战游戏列表采集与价格监控(附JSON导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集steam商店游戏列表数据·sqlite数据库存放采集数据·价格监控游戏推荐市场分析
老蒋每日coding1 小时前
LangGraph:从入门到Multi-Agent超级智能体系统进阶开发
开发语言·python
岚天start1 小时前
Python HTTP服务器添加简单用户名密码认证的三种方案
服务器·python·http
cuber膜拜1 小时前
Weaviate 简介与基本使用
数据库·python·docker·向量数据库·weaviate