1.作用
mysqlclient是python操作数据库的驱动
2. 操作
安装mysqlclient
sudo pip3 install mysqlclient
操作数据库
# mysqlclient Mysql驱动
import MySQLdb
# connect() 方法用于创建数据库连接
# host 主机地址
# port 端口号
# user 用户名
# passwd 密码
# db 数据库
# 创建连接之后,还要创建游标
conn = MySQLdb.connect(
host = 'localhost',
port = 3306,
user = 'mgt',
passwd = '1234567',
db = 'test',
)
# cursor() 创建游标,操作数据库
cur = conn.cursor()
# execute() 执行sql语句
# 创建数据表
cur.execute("create table student(id int, name varchar(20), score int, age int)")
# 插入数据
cur.execute("insert into student values('1', 'Tommy', '80', '18')")
cur.execute("insert into student values('2', 'Maria', '70', '19')")
cur.execute("insert into student values('1', 'Laura', '90', '17')")
# 插入多条数据
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
('3','Tom','70','16'),
('3','Jack','71','17'),
('3','Yaheng','72','9'),
])
# 更新数据
cur.execute("update student set score = '25' where name = 'Tommy'")
# 删除数据
cur.execute("delete from student where age = '18'")
# close() 关闭游标
cur.close()
# 提交事务
conn.commit()
# close() 关闭连接
conn.close()
网友评论