MySQL基于TCP协议之上开发,但网络连接后,传输的数据必须遵守MySQL协议。
封装好MySQL协议的包,即为驱动程序
pip install pysysql
1、mysqldb 对MySQL的C client封装实现,仅支持Python2,但不支持Python3
2、MySQL官方的连接驱动--->mysql-connector-python
3、pymysql(常使用的)
语法兼容MySQLdb,使用python写的库,支持python3
官方网址:https://pypi.org/project/PyMySQL/
API: https://pymysql.readthedocs.io/en/latest/modules/index.html
import pymysql
conn = pymysql.connect( # conn为连接MySQL数据库类的一个实例
host="localhost",
database"fresh",
port="3306",
user="root",
password=""
)
另外需要注意,数据库相关操作的返回结果以元组形式,若以kv方式返回,连接实例,定义
cursorclass=pymysql.cursors.DictCursor
print(conn)
cur = conn.cursor()
cur.execute("show databases;")
for i in cur:
print(i)
cur.close() # 关闭游标
conn.close() # 断开连接
import pymysql
conn = pymysql.connect(
host="localhost",
user="root",
password="")
cur = conn.cursor()
cur.execute("create database x01")
conn.select_db("x01")
cur.execute("create table stu (name varchar(255), class varchar(255))")
cur.execute("desc stu")
for i in cur:
print(i)
print("-------------")
cur.execute("alter table stu add column id int auto_increment primary key")
cur.execute("desc stu")
for i in cur:
print(i)
cur.execute("show tables")
for i in cur:
print(i)
print("-------------")
cur.execute("create table class (id int auto_increment primary key, name varchar(255), url varchar(255))")
cur.execute("show tables")
for i in cur:
print(i)
cur.execute("drop database x01")
cur.close()
conn.close()
create database x01; #创建库
use x01 #使用库
create table t(id int,name varchar(20)); #创建表
import pymysql
conn = pymysql.connect(
host="localhost",
user="root",
password="1234",
db="x01")
cur = conn.cursor()
cur.execute("insert into t(id,name) values(1,'张三')")
cur.execute("insert into t(id,name) values(2,'李四'),(3,'王五'),(4,'赵六')")
#确定数据插入,事务提交
conn.commit()
import pymysql
conn = pymysql.connect(
host="localhost",
user="root",
password="",
db="x01")
cur = conn.cursor()
sql = "insert into t(id,name) values(%s,%s)"
val = (5, '钱七')
cur.execute(sql,val)
conn.commit()
#将数据封装为对象,进行赋值调用方式批量插入数据,使用 executemany() 方法,该方法的第二个参数是一个元组列表,包含了我们要插入的数据:
import pymysql
conn = pymysql.connect(
host="localhost",
user="root",
password="",
db="x01")
cur = conn.cursor()
sql = "insert into t(id,name) values(%s,%s)"
val = [(101, 'aaa'), (102, 'bbb'), (103, 'ccc'), (104, 'ddd')]
cur.executemany(sql, val)
conn.commit()
print(cur.rowcount, "条记录插入成功。")
print(cur.rowcount, "条记录插入成功")
cur.execute("delete from t where id=1")
## 放弃删除数据
conn.rollback()
cur.execute('select * from t')
for i in cur:
print(i)
cur.execute('select * from tb1')
result = cur.fetchall()
for i in result:
print(i)
import pymysql
conn = pymysql.connect("localhost", "root", "", "x01")
cur = conn.cursor()
try:
i = 100
cur.callproc("proc1", (i,))
except Exception as e:
conn.rollback() #回滚
print(e)
else:
conn.commit() #提交
cur.close() #关闭游标
conn.close() #断开连接