2022年 11月 3日

python访问MySQL

1. 简介

使用pymysql模块:

 pip install pymysql
  • 1

2. 基本操作

增删改

import pymysql
# 定义数据库连接信息
config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'root',
    'password': '',
    'database': 'python',
    'charset': 'utf8'
    }

# 获取连接
conn = pymysql.connect(**config)

# 获取游标,相当于java中的Statement
cursor = conn.cursor()

# 执行sql

sql = ''' insert into t_user (username,password,age,height) values (%s,%s,%s,%s) '''

num = cursor.execute(sql, ['alice', '123', 18, 175.2]) # 为占位符%s赋值
print(num)

# 提交事务

conn.commit()

# 关闭资源
cursor.close()
conn.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

查询


# 获取游标,相当于java中的Statement
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 可以指定cursor的类型为字典,查询 结果为Dict类型
# 执行sql
sql = ''' selectid,username,password,age,height from t_user '''
cursor.execute(sql)

# 获取查询结果
print(cursor.fetchone()) # 每次读取一条,返回的是元组
print(cursor.fetchone())
print(cursor.fetchmany(2)) # 获取多条
print(cursor.fetchall()) # 获取所有

for u in cursor.fetchall():
    print(u['username'], u['age'])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15