接口测试--Python操作MySql数据库

1.首先在python中安装驱动模块:pip install pymysql

2.连接到数据库:

使用pymysql.connect(主机名host,端口port,登录用户user,登录密码password,数据库database)

mySqlCon = pymysql.connect(host ='localhost', port =3306 , user ='root',password ='123123',database ='edu_app')

3.创建一个游标:

cur = mySqlCon.cursor()

4.执行对应的sql语句:

selectSql = 'select * from course where name = \'test\''

res = cur.execute(selectSql)

5.打印sql执行结果:

print(res)

6.获取一条记录:

data_one = cur.fetchone()

print(data_one)

7.获取多条记录:

data_all = cur.fetchall()

print(data_all)



实际代码如下:

import pymysql.cursors

#1.连接到数据库

mySqlCon = pymysql.connect(host ='ip', port =3306 , user =user,password ='123123',database ='edu_app')

#2.创建一个游标

cur = mySqlCon.cursor()

#3.执行对应的sql(sele)excute

selectSql ='select * from course where name = \'test\''

res = cur.execute(selectSql)

#4.打印查询结果(一共有几条数据)

print(res)

#5.获取一条数据

data_one = cur.fetchone()

print(data_one)

#6.获取多条数据

data_all = cur.fetchall()

print(data_all)


返回结果如下:


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容