01-MySQL与Python交互

1.Python与MySQL交互流程

2.Python与MySQL交互基本步骤

  1. 引入pymysql模块,该模块python解释器不自带,需要单独安装:pip3 install pymysql 代码中引入: from pymysql import *

  2. 创建Connection对象,用于建立与数据库的连接 创建数据库连接 self.conn = connect(host='localhost', port=3306, database='jing_dong', user='root', password='themelove', charset='utf8')

  3. 通过connection对象获取cursor对象 conn.cursor()

  4. cursor.execute(sql, agrs) 执行sql语句,返回值为执行语句影响的记录数 例: count = cursor.execute("""select * from goods where brand_id=2""") cursor.fetchall()

  5. 通过cursor.fetchone()、cursor.fetchmany(count)、cursor.fetchall()获取执行结果 cursor.fetchone():获取一条记录,返回值为元祖 cursor.fetchmany(count):获取count条记录,返回值为元祖,每条记录也对应一个元祖 cursor.fetchall():获取所有记录,返回值为元祖,每条记录也对应一个元祖

  6. 使用完毕关闭cursor和connection对象 cursor.close() conn.close()

3.Connection 对象

用于建立与数据库的连接

4.Cursor对象

用于执行sql语句,使用频度最高的语句为select、insert、update、delete

5.SQL语句的注入

python与MySQL交互实现增删改查:

Last updated