Python pymysql操作MySQL详细

 

1、使用

1.1 简单使用

import pymysql

# 创建连接
con = pymysql.connect(
                      host='localhost',
                      port=3306,
                      user='root',
                      password='123456',
                      database='test',
                      charset='utf8'
)
# 创建游标
cursor = con.cursor()

# 执行新增SQL,返回受影响行数
row1 = cursor.execute("insert into user (username, password) values ('username3','password3')")
print(row1)

# 执行更新SQL,返回受影响行数
row2 = cursor.execute("update user set password = '123456' where id > 2;")
# 执行查询SQL
res = cursor.execute("SELECT * FROM user;")
result = cursor.fetchall()
for info in result:
  print(info[0], info[1])
# 提交,不然无法保存新增或者更新的数据
con.commit()
# 关闭游标
cursor.close()
# 关闭连接
con.close()

注意:数据库表中存在中文时,创建连接需要指定charset='utf8',否则中文显示会乱码。 其中cursor.fetchall()是获取所有结果集,如果只有一条结果集,可以使用cursor.fetchone()

1.2 封装工具类

为了使用方便,可以直接封装成工具类:

import pymysql


class MysqlHelper:
  def __init__(self, config):
      self.host = config["host"]
      self.port = config["port"]
      self.user = config["user"]
      self.password = config["password"]
      self.db = config["db"]
      self.charset = config["charset"]
      self.con = None
      self.cursor = None

  def create_con(self):
      """
      创建连接
      """
      try:
          self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
                                     database=self.db, charset='utf8')
          self.cursor = self.con.cursor()
          return True
      except Exception as e:
          print(e)
          return False

  #
  def close_con(self):
      """
      关闭链接
      """
      if self.cursor:
          self.cursor.close()
      if self.con:
          self.con.close()

  # sql执行
  def execute_sql(self, sql):
      """
      执行插入/更新/删除语句
      """
      try:
          self.create_con()
          print(sql)
          self.cursor.execute(sql)
          self.con.commit()
      except Exception as e:
          print(e)
      finally:
          self.close_con()

  def select(self, sql, *args):
      """
      执行查询语句
      """
      try:
          self.create_con()
          print(sql)
          self.cursor.execute(sql, args)
          res = self.cursor.fetchall()
          return res
      except Exception as e:
          print(e)
          return False
      finally:
          self.close_con()

使用工具类:

config = {
  "host": 'localhost',
  "port": 3306,
  "user": 'root',
  "password": '123456',
  "db": 'test',
  "charset": 'utf8'
}
db = MysqlHelper(config)
db.execute_sql("insert into user (username, password) values ('username4','password4')")
db.select("SELECT * FROM user;")

关于Python pymysql操作MySQL详细的文章就介绍至此,更多相关Python pymysql操作MySQL内容请搜索编程宝库以前的文章,希望大家多多支持编程宝库

前言小时候一直有一个想成为钢琴家的梦想,最近在网上看到了一个开源的钢琴演奏网页autopiano,可以支持键盘按键弹奏、鼠标点击弹奏。首先一起来看看最终实现的演奏效果:下面,我们就开始介绍 ...