mysql与pyhton交互五:python操作sql查询操作

python访问数据库总流程
访问需要的相关模块介绍
python查询代码

python访问数据库总流程

通过python DB API访问数据库

1.创建connection
2.获取cursor
3.执行命令
4.关闭cursor
5.关闭connection


访问需要的相关模块介绍

1.pymysql模块
2.connection对象
3.cursor对象

1.需要把pymysql模块导入
from pymysql import *
2.connection对象

用于建立与数据库之间的连接

con=connect(参数列表)

参数host:连接的mysql主机
参数port:连接的mysql主机的端口c
参数datbase:数据库的名称
参数user:连接的用户名
参数password:连接的密码
参数charset:通信采用的编码方式,推荐使用uft8

对象可操作的方法
close() 关闭连接
commit() 提交
cursor()返回cursor对象,用于执行sql语句并获得结果

3.cursor对象
cs1=conn.cursor()

1.用于执行sql语句,使用频度最高的语句为select,insert,update,delete(增删改查)
2.获取cursor对象:调用connection对象的cursor()方法

对象可操作的方法
close() 关闭

execute(operation[,parameters])
执行语句,返回受影响的行数,主要用于执行sql语句

fetchone()
执行查询语句时,获取查询结果的第一行数据,返回一个元组
fetchall()
执行查询语句时,获取查询结果的所有行数据,一行构成一个元组,再将这些元组装入一个元组返回


python查询代码

1.查询一行代码
2.查询所有行代码

1.查询一行代码(fetchone)
#引用模块
from pymysql import *

def main():

    #创建connect连接
    conn=connect(host='localhost',port=3306,user='root',password='980928',database='jing_dong',charset='utf8')

    #获取cursor对象
    cs1=conn.cursor()

    #执行select语句,execute返回一个行数
    count=cs1.execute('select id,name from goods where id>=4')

    #打印
    print("查询到%d条数据" % count)
    for i in range(count):
        result=cs1.fetchone()
        print(result)

    #关闭cursor对象
    cs1.close()

    #关闭connection连接
    conn.close()

if __name__ == '__main__':
    main()

结果如图:
mysql与pyhton交互五:python操作sql查询操作

2.查询所有行代码(fetchall)
#引用模块
from pymysql import *

def main():

    #创建connect连接
    conn=connect(host='localhost',port=3306,user='root',password='980928',database='jing_dong',charset='utf8')

    #获取cursor对象
    cs1=conn.cursor()

    #执行select语句,execute返回一个行数
    count=cs1.execute('select id,name from goods where id>=4')
    
    x = cs1.fetchall()		//查询所有
    print(x)

    #关闭cursor对象
    cs1.close()

    #关闭connection连接
    conn.close()

if __name__ == '__main__':
    main()

结果如图:
mysql与pyhton交互五:python操作sql查询操作