python的mysql-connector和pymysql
pip3 install pymysql
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(
host=“你的数据库地址”,
user=“用户名”,password=“密码”,
database=“数据库名”,
charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
# 得到一个可以执行SQL语句并且将结果作为字典返回的游标
#cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定义要执行的SQL语句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8; #注意:charset='utf8' 不能写成utf-8
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
execute帮我们做字符串拼接
# 将以下代码
sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)
res=cursor.execute(sql)
# 改为
sql="select * from userinfo where name=%s and password=%s"
#%s需要去掉引号,pymysql会自动加上
res=cursor.execute(sql,[user,pwd])
import pymysql
conn = pymysql.connect(
host='192.168.0.103',
port=3306,
user='root',
password='123',
database='xing',
charset='utf8'
)
# 获取一个光标
cursor = conn.cursor()
# 定义要执行的sql语句
sql = 'insert into userinfo(user,pwd) values(%s,%s);'
data = [
('july', '147'),
('june', '258'),
('marin', '369')
]
# 拼接并执行sql语句
cursor.executemany(sql, data)
# 涉及写操作要注意提交
conn.commit()
# 关闭连接
cursor.close()
conn.close()
import pymysql
conn =pymysql.connect(
host ='192.168.0.103',
port = 3306,
user = 'root',
password ='123',
database ='xing',
charset ='utf8'
)
cursor =conn.cursor() #获取一个光标
sql ='insert into userinfo (user,pwd) values (%s,%s);'
name = 'wuli'
pwd = '123456789'
cursor.execute(sql, [name, pwd])
conn.commit()
cursor.close()
conn.close()
import pymysql
# 建立连接
conn = pymysql.connect(
host="192.168.0.103",
port=3306,
user="root",
password="123",
database="xing",
charset="utf8"
)
# 获取一个光标
cursor = conn.cursor()
# 定义将要执行的SQL语句
sql = "insert into userinfo (user, pwd) values (%s, %s);"
name = "wuli"
pwd = "123456789"
# 并执行SQL语句
cursor.execute(sql, [name, pwd])
# 涉及写操作注意要提交
conn.commit()
# 关闭连接
# 获取最新的那一条数据的ID
last_id = cursor.lastrowid
print("最后一条数据的ID是:", last_id)
cursor.close()
conn.close()
import pymysql
# 建立连接
conn = pymysql.connect(
host="192.168.0.103",
port=3306,
user="root",
password="123",
database="xing",
charset="utf8"
)
# 获取一个光标
cursor = conn.cursor()
# 定义将要执行的SQL语句
sql = "delete from userinfo where user=%s;"
name = "june"
# 拼接并执行SQL语句
cursor.execute(sql, [name])
# 涉及写操作注意要提交
conn.commit()
# 关闭连接
cursor.close()
conn.close()
import pymysql
# 建立连接
conn = pymysql.connect(
host="192.168.0.103",
port=3306,
user="root",
password="123",
database="xing",
charset="utf8"
)
# 获取一个光标
cursor = conn.cursor()
# 定义将要执行的SQL语句
sql = "update userinfo set pwd=%s where user=%s;"
# 拼接并执行SQL语句
cursor.execute(sql, ["july", "july"])
# 涉及写操作注意要提交
conn.commit()
# 关闭连接
cursor.close ()
conn.close ()
import pymysql
conn = pymysql.connect (
host='192.168.0.103',
port=3306,
user='root',
password='123',
database='xing',
charset='utf8'
)
# 获取一个光标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 返回字典数据类型
# 定义将要执行的sql语句
sql = 'select user,pwd from userinfo;'
# 拼接并执行sql语句
cursor.execute(sql)
# 取到查询结果
ret1 = cursor.fetchone() # 取一条
ret2 = cursor.fetchmany(3) # 取三条
ret3 = cursor.fetchone() # 取一条
cursor.close()
conn.close()
print(ret1)
print(ret2)
print(ret3)
# 可以获取指定数量的数据
cursor.fetchmany(3)
# 光标按绝对位置移动1
cursor.scroll(1, mode="absolute")
# 光标按照相对位置(当前位置)移动1
cursor.scroll(1, mode="relative")
import pymysql
# 建立连接
conn = pymysql.connect(
host="192.168.0.103",
port=3306,
user="root",
password="123",
database="xing",
charset="utf8"
)
# 获取一个光标
cursor = conn.cursor()
# 定义将要执行的SQL语句
sql1 = "insert into userinfo (user, pwd) values (%s, %s);"
sql2 = "insert into hobby (id, hobby) values (%s,%s);"
user = "july1"
pwd = "july1"
id = "我是错误的id" #id = "3"
hobby = "打游戏"
try:
# 拼接并执行SQL语句
cursor.execute(sql1, [user, pwd])
print(sql1)
cursor.execute(sql2, [id, hobby]) # 报错的SQL语句
# 涉及写操作注意要提交
conn.commit()
except Exception as e:
print(str(e))
# 有异常就回滚
conn.rollback()
# 关闭连接
cursor.close()
conn.close()
python -m pip install mysql-connector
连接MySQL
主要是使用mysql.connector模块的connect函数,需要注意参数的名称。
import mysql.connector
# 接收参数:user, password, host, port=3306, unix_socket and database
# 返回一个MySQLConnection Object
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='test'
)
执行SQL命令
执行sql命令之前,需要先创建一个查询,调用一下cursor()方法,这个方法名光标的意思,可以理解为,命令行中,执行sql语句之前,先要有一个光标行,在光标行中进行操作。
调用cursor()返回的结果就是光标行(cmd,简称cmd),然后调用cmd的execute()方法,传入要执行的sql即可,不过需要注意的是,执行sql的结果,执行的结果仍旧保存在cmd中。
select查询操作
执行select操作,使用fetchall()一次性取回所有的结果集。
import mysql.connector
# 接收参数:user, password, host, port=3306, unix_socket and database
# 返回一个MySQLConnection Object
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='test'
)
# 创建一个查询
cmd = conn.cursor()
# 执行一条原生的SQL语句,执行结果保存在cmd中,没有返回值
cmd.execute("select id, name, age from stu")
# 可以使用fetchall(),获取所有的查询结果集,返回值为一个tuple,每一个元素是一个list
res = cmd.fetchall()
print(res)
# [(1, 'xinming', 20), (2, 'renmin', 30), (3, 'xi', 10)]
执行select操作,使用fetchone()每次只取一条记录
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='test'
)
cmd = conn.cursor()
cmd.execute("select id, name, age from stu")
# 使用fetchone()返回一条结果集,每调用一次之后,内部指针会指向下一条结果集
print(cmd.fetchone()) # (1, 'xinming', 20)
print(cmd.fetchone()) # (2, 'renmin', 30)
print(cmd.fetchone()) # (3, 'xi', 10)
执行select操作,使用fetchmany(num)指定每次返回的num条结果集
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='test'
)
cmd = conn.cursor()
cmd.execute("select * from stu")
res = cmd.fetchmany(2) # 指定返回2条记录
print(res)
# [(1, 'xinming', 20), (2, 'renmin', 30)]
res = cmd.fetchmany(1) # 指定返回1条记录
print(res)
# [(3, 'xi', 10)]
insert、update、delete操作
insert、update、delete操作,也都是使用execute方法,只需要将要执行的sql语句传入即可。
可以在执行增删改操作之后,rowcount属性保存着受影响的记录数。
每次插入一条数据
import mysql.connector
# 接收参数:user, password, host, port=3306, unix_socket and database
# 返回一个MySQLConnection Object
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='test'
)
# 创建一个查询
cmd = conn.cursor()
# 执行原生SQL语句
cmd.execute("insert into stu (id, name, age) values (4, 'LiBai', 99)")
print(cmd.rowcount) # 1
cmd.execute("select * from stu")
res = cmd.fetchall()
print(res)
# [(1, 'xinming', 20), (2, 'renmin', 30), (3, 'LiLei', 10), (4, 'LiBai', 99)]
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='test'
)
cmd = conn.cursor()
# 注意,在SQL中的占位符,统一写%s, 具体的类型,是在tuple中,传入的参数元素类型决定
cmd.execute("select * from stu where id=%s and name=%s", (1, 'xinming'))
res = cmd.fetchall()
print(res)
# [(1, 'xinming', 20)]