1、单条数据操作

1)、常用方法

import pandas as pd
import pymysql

db = {
    'host': '192.168.1.1',  # 服务器地址
    'port': 3306,  # 端口号
    'user': 'root',  # 用户名
    'password': '12345678',  # 密码
    'db': 'database',  # 数据库
    'charset': 'utf8mb4'}  # 编码


conn = pymysql.connect(**db)  # 连接数据库
cursor = conn.cursor()  # 生成游标,通过指针操作mysql
curs_sql = f'select * from tb_name where id_name="{id_name}"'  #  sql语句。
try:
    cursor.execute(curs_sql)  # 执行sql语句
except:
    conn.rollback()  # 如果发生异常,就回滚
conn.commit()  # 提交事务
cursor.close()  # 关闭游标
conn.close()  # 关闭数据库连接

注:此方法可能存在转义问题,比如数据种存在单双引号等,可能使得sql语句引号混乱发生冲突,所以如果所筛选的字段数据中带有引号,最好在字符串引号前面加上\\\三个转义符。

2)推荐方法:

insert_data = ('数据')  # 元组格式,与下面sql语句中的%s 一 一 对应
curs_sql = f'select * from tb_name where id_name=%s'  #  sql语句
try:
    cursor.execute(curs_sql, insert_data)  # 执行sql语句
except:
    conn.rollback()  # 如果发生异常,就回滚

此方法不存在转义问题

2、多条数据操作

此方法不存在转义问题,内部机制会自行处理

import pandas as pd
import pymysql

db = {
    'host': '192.168.1.1',  # 服务器地址
    'port': 3306,  # 端口号
    'user': 'root',  # 用户名
    'password': '12345678',  # 密码
    'db': 'database',  # 数据库
    'charset': 'utf8mb4'}  # 编码


conn = pymysql.connect(**db)  # 连接数据库
cursor = conn.cursor()  # 生成游标,通过指针操作mysql
sql = "update tb_name set g_rank=%s, number=%s where name=%s"  # sql语句,此处数据用%s代替,与后面列表中数据是 一 一 对应关系

try:
    cursor.executemany(sql, [(g_rank1, number1, name1),(g_rank2, number2, name2),(g_rank3, number3, name3)......])  # 批量插入数据,与sql中%s是一一对应关系
except:
    conn.rollback()  # 如果发生异常,就回滚
conn.commit()  # 提交事务
cursor.close()  # 关闭游标
conn.close()  # 关闭数据库连接

 

posted on 2020-03-20 18:42  jaysonteng  阅读(235)  评论(0编辑  收藏  举报