Python与数据库python与MySQL的交互

Python与MySQL的交互操作

安装mysql模块

# pip install -i https://pypi.doubanio.com/simple/ python-mysql # 支持 2.x版本
pip install -i https://pypi.doubanio.com/simple/ mysql-connector # 3.x

在文件中引入模块

import mysql.connector

关于Connection对象与Cursor对象

Connection对象

  用于建立与数据库的连接

  创建对象:调用connect()方法
  conn=connect(参数列表)
  参数host:连接的mysql主机,如果本机是'localhost'
  参数port:连接的mysql主机的端口,默认是3306
  参数db:数据库的名称
  参数user:连接的用户名
  参数password:连接的密码
  参数charset:通信采用的编码方式,默认是'gb2312',
要求与数据库创建时指定的编码一致,否则中文会乱码

对象的方法
close()关闭连接
commit()事务,所有任务需要提交才会生效
rollback()事务,放弃之前的操作
cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor 对象
  执行sql语句

  创建对象:调用Connection对象的cursor()方法
  cursor1=conn.cursor()

  对象的方法
  close()关闭
  execute(operation [, parameters ])执行语句,返回受影响的行数
  fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
  next()执行查询语句时,获取当前行的下一行
  fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
  scroll(value[,mode])将行指针移动到某个位置
    mode表示移动的方式
    mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,  value为负则向上移动
  mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0

对象的属性
rowcount只读属性,表示最近一次execute()执行后受影响的行数
connection获得当前连接对象

连接 数据库

import mysql.connector
mydb = mysql.connector.connect(
  host = "localhost" , # 数据库主机名
  port = "3306" ,
  user = "root" , # 数据库用户名
  passwd = "123456" , # 数据库密码
)
print(mydb)

创建数据库 - CREATE DATABASE

# 创建一个名为 student_db 的数据库
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE student_db")
# 查看数据库是否创建成功
mycursor.execute("SHOW DATABASES")
for x in mycursor:
    print(x)

创建数据表 -- CREATE TABLE

# 创建数据表前,需要确保数据库已存在
import mysql.connector
mydb = mysql.connector.connect(
  host = "localhost" , # 数据库主机名
  port = "3306" ,
  user = "root" , # 数据库用户名
  passwd = "123456" , # 数据库密码
  database = "student_db" # 数据库
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE student (id INT(11),name VARCHAR(25),sex VARCHAR(10))")
# 查看数据表是否创建成功
mycursor.execute("SHOW TABLES")
for x in mycursor:
    print(x)

主键设置 -- INT AUTO_INCREMENT PRIMARY KEY

"""创建表的时候我们一般都会设置一个主键(PRIMARY KEY),
我们可以使用 "INT AUTO_INCREMENT PRIMARY KEY" 语句来创建一个主键,
主键起始值为 1,逐步递增。
如果我们的表已经创建,我们需要使用 ALTER TABLE 来给表添加主键:"""
mycursor.execute("ALTER TABLE student MODIFY COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
mycursor.execute("DESC student")
for x in mycursor:
    print(x)

插入数据 -- INSERT INTO 

##  单条数据的插入
import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()
sql = "INSERT INTO student (id,name,sex) VALUES (%s,%s,%s)"
val = (2020001,"Tom","male")
mycursor.execute(sql, val)
mydb.commit() # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")

## 批量数据的插入
sql = "INSERT INTO student (id,name,sex) VALUES (%s,%s,%s)"
val2 = (2020002,"Tony","male")
val3 = (2020003,"Alice","female")
val4 = (2020004,"Jim","male")
val5 = (2020005,"Eric","female")
val6 = (2020006,"Smish","male")
val7 = (2020007,"Candy","male")
val8 = (2020008,"Bonnie","female")
val9 = (2020009,"Pluto","female")
val10 = (2020010,"Clinton","female")
vals = (val2,val3,val4,val5,val6,val7,val8,val9,val10)
mycursor.executemany(sql, vals)
mydb.commit() # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")

数据查询  selimport mysql.connector

mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()

###
# fetchall() 获取所有记录

mycursor.execute("SELECT * FROM student") results = mycursor.fetchall() for result in results: print(result)

### 读取指定的字段数据
mycursor.execute("SELECT name, sex FROM student")
results = mycursor.fetchall()
for result in results:
print(result)

### 如果我们只想读取一条数据,可以使用 fetchone() 方法
mycursor.execute("SELECT name, sex FROM student")
result = mycursor.fetchone()
print(result)

where 条件语句

import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()
# 插入单行数据
sql = "INSERT INTO student (id,name,sex) VALUES (%s,%s,%s)"
val = (2020011,"Tom","female")
mycursor.execute(sql, val)
mydb.commit() # 数据表内容有更新,必须使用到该语句
# 数据查询
mycursor.execute("SELECT * FROM student WHERE name='Tom'")
results = mycursor.fetchall()
for result in results:
    print(result)

使用通配符 %

import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()
# 数据查询
mycursor.execute("SELECT * FROM student WHERE sex LIKE 'fe%'")
results = mycursor.fetchall()
for result in results:
    print(result)

排序 orderBy

排序 -- ORDER BY
"""
查询结果排序可以使用 ORDER BY 语句,默认的排序方式为升序,
关键字为 ASC,如果要设置降序排序,可以设置关键字 DESC。
"""
import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()
# 数据排序 -- 默认升序 ASC
# mycursor.execute("SELECT * FROM student ORDER BY name")
mycursor.execute("SELECT * FROM student ORDER BY name DESC") # 降序排序
results = mycursor.fetchall()
for result in results:
    print(result)

设置查询的数据量与位置-- LIMIT vs OFFSET

# 如果我们要设置查询的数据量,可以通过 "LIMIT" 语句来指定
import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM student LIMIT 4")
results = mycursor.fetchall()
for result in results:
    print(result)

指定起始位置 - OFFSET
# 0 为 第一条,1 为第二条,以此类推

mycursor.execute("SELECT * FROM student LIMIT 4 OFFSET 3")
results = mycursor.fetchall()
for result in results:
  print(result)

数据删除

# 删除记录使用 "DELETE FROM" 语句
import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
# 插入单行数据
mycursor = mydb.cursor()
sql = "INSERT INTO student (id,name,sex) VALUES (%s,%s,%s)"
val = (2020011,"Tom","female")
mycursor.execute(sql, val)
mydb.commit() # 数据表内容有更新,必须使用到该语句
# 删除单行数据
mycursor = mydb.cursor()
sql = "DELETE FROM student WHERE id='2020011'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, " 条记录删除")

"""注意:
要慎重使用删除语句,删除语句要确保指定了 WHERE 条件语句,
否则会导致整表数据被删除。
为了防止数据库查询发生 SQL 注入的攻击,
我们可以使用 %s 占位符来转义删除语句的条件:"""
import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
# 删除单行数据
mycursor = mydb.cursor()
sql = "DELETE FROM student WHERE id= %s"
value = ("2020007",) # 元组模式传递
mycursor.execute(sql,value)
mydb.commit()
print(mycursor.rowcount, " 条记录删除")

更新数据 update

import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
# 删除单行数据
mycursor = mydb.cursor()
sql = "UPDATE student SET name= %s WHERE name= %s"
value = ("Choocelate","Smish") # 元组模式传递
mycursor.execute(sql,value)
mydb.commit()
print(mycursor.rowcount, " 条记录被修改")

数据库与数据表的删除 -- drop

# 删除表 -- DROP TABLE
"""
删除表使用 "DROP TABLE" 语句, IF EXISTS 关键字是用于判断表是否存在,
只有在存在的情况才删除:"""
import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()
sql = "DROP TABLE IF EXISTS student" # 删除数据表 student
mycursor.execute(sql)
# 查看数据库是否被删除
mydb = mysql.connector.connect(
    host = "localhost" , # 数据库主机名
    port = "3306" ,
    user = "root" , # 数据库用户名
    passwd = "123456" , # 数据库密码
    database = "student_db" # 数据库
)
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
    print(x)
原文地址:https://www.cnblogs.com/Skypeduty1225/p/15608334.html