第十课:MySql数据库

88 阅读2分钟

自行安装mysql和navicat

1.python连接Mysql数据库

python想要操作mysql,必须要使用到一个中间件,或者叫做驱动程序,驱动程序有很多,比如:

  • mysqldb(只在python2中有用)
  • Mysqlclient
  • Pymysql

在这里,我们使用pymysql

pip install pymysql
import pymysql

# 1.使用pymysql去连接数据库
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='zhangjing1234', database='pachong')
# 2.如果要操作数据库,还需获取db上面的cursor对象
cursor = db.cursor()
# 3.执行sql语句
cursor.execute("select * from article")
# 4.提取结果当中的一条数据
result = cursor.fetchone()
print(result)

2.插入数据

import pymysql

# 1.使用pymysql去连接数据库
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='zhangjing1234', database='pachong')
# 2.创建一个游标对象
cursor = db.cursor()
# 3.sql语句
# 数据写死了,不好
# sql = "insert into article(id, title, content) values (null, '银苹果', '讲诉了农名种植银苹果的历程')"
# cursor.execute(sql)
sql = "insert into article(id, title, content) values (null, %s, %s)"
title = '铜苹果'
content = '讲诉了农名伯伯种植铜苹果的心酸过程'
# 4.执行sql语句
cursor.execute(sql, (title, content))
# 5.提交
db.commit()
# 6.关闭连接
db.close()

3.查找数据

import pymysql

# 1.使用pymysql去连接数据库
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='zhangjing1234', database='pachong')

# 2.创建一个游标对象
cursor = db.cursor()

# 3.sql语句
# 数据写死了,不好
# sql = "insert into article(id, title, content) values (null, '银苹果', '讲诉了农名种植银苹果的历程')"
# cursor.execute(sql)

sql = "select * from article where id>=2"

# 4.执行sql语句
cursor.execute(sql)

# result = cursor.fetchone()      # (2, '银苹果', '讲诉了农名种植银苹果的历程')
# result = cursor.fetchall()      # ((2, '银苹果', '讲诉了农名种植银苹果的历程'), (3, '铜苹果', '讲诉了农名伯伯种植铜苹果的心酸过程'))
result = cursor.fetchmany(1)      # ((2, '银苹果', '讲诉了农名种植银苹果的历程'),)

print(result)

# 5.提交
db.commit()

# 6.关闭连接
db.close()

执行完sql语句后,可以使用以下三个方法来提取数据:

  1. fetcheone:提取第一条数据。
  2. fetchall:提取select语句获取到的所有数据。
  3. fetchmany:提取指定条数的数据。

4.删除数据

import pymysql

# 1.使用pymysql去连接数据库
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='zhangjing1234', database='pachong')

# 2.创建一个游标对象
cursor = db.cursor()

# 3.sql语句
sql = "delete from article where id=3"

# 4.执行sql语句
cursor.execute(sql)

# 5.提交
db.commit()

# 6.关闭连接
db.close()

5.更新数据

import pymysql

# 1.使用pymysql去连接数据库
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='zhangjing1234', database='pachong', charset='utf8')

# 2.创建一个游标对象
cursor = db.cursor()

# 3.sql语句
sql = "update article set title='铜苹果' where id=2"

# 4.执行sql语句
cursor.execute(sql)

# 5.提交
db.commit()

# 6.关闭连接
db.close()