1、查看Python中是否安装好了pymysql模块
在Windows控制台输入pip list可以查看是否有pymysql模块,没有安装可以使用pip进行安装
pip install pymysql
2、连接数据库
import pymysql
def db_connect():
# 打开数据库连接,参数分别为数据库地址、数据库用户名、密码、数据库名称
db = pymysql.connect('127.0.0.1', 'root', 'root', 'mysql_test')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
# 使用execute()方法执行SQL查询
cursor.execute("select version()")
# 使用fetchall()方法获取单条数据
data = cursor.fetchone()
print(f'Database version : {data[0]}')
# 关闭数据库连接
db.close()
# 主方法
def main():
db_connect()
# 启动
if __name__ == '__main__':
main()
连接成功后执行结果如下:
3、创建数据表
import pymysql
def create_table():
db = pymysql.connect('127.0.0.1', 'root', 'root', 'mysql_test')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
# 使用execute()方法执行SQL,如果存在表就删除他
cursor.execute("drop table if exists employee")
sql = """create table employee(
first_name char(20) not null ,
last_name char(20) ,
age int,
sex char(1),
income float,
create_time datetime)"""
try:
cursor.execute(sql)
print("create table success")
except Exception as ex:
print(f'create table failed, case:{ex}')
finally:
db.close()
# 主方法
def main():
create_table()
# 启动
if __name__ == '__main__':
main()
执行结果如下:
数据库里查看表结构:
4、数据库插入
import pymysql
import datetime
def insert_record():
db = pymysql.connect('127.0.0.1', 'root', 'root', 'mysql_test')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
# 插入sql语句
sql = "insert into employee(first_name, last_name, age, sex, income, "\
"create_time) values ('%s', '%s', '%d', '%c', '%d', '%s' )"\
% ('xiao', 'zhi', 22, 'M', 30000, datetime.datetime.now())
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库
db.commit()
print("insert success")
except Exception as ex:
print(f'insert into mysql failed, case:{ex}')
# 发生错误回滚
db.rollback()
finally:
# 关闭数据库连接
db.close()
# 主方法
def main():
insert_record()
# 启动
if __name__ == '__main__':
main()
执行结果如下:
数据库内容:
5、数据库查询
Python使用fetchone()获取单条数据,使用fetchall()方法获取多条数据
- fetchone():该方法获取下一个查询结果集。结果集是一个对象
- fetchall():接收全部返回结果行
- rowcount():只读属性,返回执行execute()方法后影响的行数
import pymysql
def query_data():
db = pymysql.connect('127.0.0.1', 'root', 'root', 'mysql_test')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
# 查询sql语句
sql = "select * from employee"
try:
# 执行sql语句
cursor.execute(sql)
# 返回所有记录列表
results = cursor.fetchall()
for row in results:
first_name = row[0]
last_name = row[1]
age = row[2]
sex = row[3]
income = row[4]
create_time = row[5]
# 输出结果
print(f'first_name={first_name}, last_name={last_name}, age ={age},'
f'sex={sex}, income={income}, create_time={create_time}')
except Exception as ex:
print(f'Error: unable to fecth data, Error info:{ex}')
finally:
# 关闭数据库连接
db.close()
# 主方法
def main():
query_data()
# 启动
if __name__ == '__main__':
main()
查询结果如下:
6、数据库更新
import pymysql
def update_table():
db = pymysql.connect('127.0.0.1', 'root', 'root', 'mysql_test')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
# 插入sql语句
sql = "update employee set age = age + 2 where sex = '%s'" % 'M'
try:
# 执行sql语句
cursor.execute(sql)
# 提交数据库执行
db.commit()
print("update success")
except Exception as ex:
print(f'update mysql table failed. Case:{ex}')
db.rollback()
finally:
# 关闭数据库连接
db.close()
# 主方法
def main():
update_table()
# 启动
if __name__ == '__main__':
main()
执行结果如下:
数据库表:
7、数据库删除
import pymysql
def delete_record():
db = pymysql.connect('127.0.0.1', 'root', 'root', 'mysql_test')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
# sql删除语句
sql = "delete from employee where age > %d" % 22
try:
# 执行sql语句
cursor.execute(sql)
# 提交数据库执行
db.commit()
print("delete success")
except Exception as ex:
print(f'delete record failed. Case:{ex}')
# 发生错误时回滚
db.rollback()
finally:
# 关闭数据库连接
db.close()
# 主方法
def main():
delete_record()
# 启动
if __name__ == '__main__':
main()
执行结果如下: