Loading

08_使用python操作mysql

用Python操作MySQL

使用步骤

1. 导入模块: import pymysql
dbconfig = {
    # 'host': 'ip',
    # 'port': 3306
    'user': 'root',
    'password': 'qwe123',
    'db': 'python3',	# 指定用哪个数据库
    'charset': 'utf8',  # 字符编码
}
2. 建立连接: conn = pymysql.connect(**dbconfig)
	# 连接是不能操作数据库的, 需要用到连接生成游标来操作
3. 创建获取游标: cur = conn.cursor()
4. 执行sql语句: cur.execute(sql)
	# sql语句都是通过这个方法执行 如 cur.execute('select * from student')
5. 获取结果: cur.fetchone()/cur.fetchmany(count)/cur.fetchall()

注意要点

  1. 在Python中执行的sql语句不需要加 '';''
  2. cur.execute(sql) 执行完后不是直接得到结果, 需要你主动云获取
  3. 和文件一样, 别忘记关闭游标与连接
  4. 事务的回滚和提交

连接查询

# python操作mysql

import pymysql


# 1. 建立连接
db_config = {
    'user': 'root',
    'password': 'qwe123',
    'db': 'python3',    # 用哪个数据库
    'charset': 'utf8',  # 指定编码
}
conn = pymysql.connect(**db_config)    # 连接

# 2. 游标
cur = conn.cursor()  # 获取游标

# 3. 执行SQL语句
# cur.execute('select * from student')

# 执行后返回值是数据的数量
# res = cur.execute('select * from student')  # 返回表中数据的数量, 即有多少条数据
# print(res)

# 获取结果
cur.execute('select * from student')

row = cur.fetchone()
while row:
    print('row'.format(row))
    row = cur.fetchone()    # 这样子, 一条一条的取, 不会造成内存爆炸

# res = cur.fetchone()       # fetchone() 每运行一次, 拿到一条数据
# print(res)
# 第运行一次, 拿到一条数据
# res = cur.fetchone()
# print(res)
# res = cur.fetchone()
# print(res)
# res = cur.fetchone()    # 没有数据拿到了, 返回None
# print(res)

# print(cur.fetchall())   # fetchall()  拿到全部的数据,            # 数据很大的话, 一下子取全部, 会造成内存爆炸

print(cur.fetchmany(3))     # fetchmany()  指定拿多少条数据, 如果表中数据没有多, 则返回全部数据

# 4. 关闭游标
cur.close()

# 5. 关闭连接
conn.close()


插入数据, (python操作mysql默认是开启了事务模式的) commit真正把数据写入到数据库中

# 用Python操作MySQL, 其默认使用了事务模式
import pymysql


# 1. 创建连接
db_config = {
    'user': 'root',
    'password': 'qwe123',
    'db': 'python3',
    'charset': 'utf8',
}
conn = pymysql.connect(**db_config) # 连接

# 2. 创建游标
cur = conn.cursor()

# 3. 执行sql语句
cur.execute('insert into stu value(1, "long", 18, "M")')    # 默认使用了事务模式, 不会立即插入, 只有当你commit的时候才会插入到数据库表中
conn.commit()   # commit # python 操作数据库默认使用了事务模式,commit的时候才会真正的把数据插入到表中去


# 4. 关闭游标
cur.close()

# 5. 关闭连接
conn.close()

上下文管理 with pymysql.connect(**dbconfig) as cur:

import pymysql

db_config = {
    'user': 'root',
    'password': 'qwe123',
    'db': 'python3',
    'charset': 'utf8',
}
conn = pymysql.connect(**db_config)
with conn.cursor() as cur:  # cur游标对象       # with 自动关闭的

# with pymysql.connect(**db_config) as cur:
    cur.execute('insert into stu value(6, "yan", 19, "F")')
# conn.commit()     # (开启了事务)提交
# conn.rollback()     # (事务回滚)回滚

posted @ 2019-09-18 10:33  未来已来,你来不来  阅读(172)  评论(0编辑  收藏  举报