Python操作mysql

python中操作mysql的步骤

引入模块

  • 在py文件中引入pymysql模块
from pymysql import *

Connection 对象

  • 用于建立与数据库的连接
  • 创建对象:调用connect()方法
conn=connect(参数列表)
  • 参数host:连接的mysql主机,如果本机是'localhost'
  • 参数port:连接的mysql主机的端口,默认是3306
  • 参数database:数据库的名称
  • 参数user:连接的用户名
  • 参数password:连接的密码
  • 参数charset:通信采用的编码方式,推荐使用utf8

对象的方法:

  • close()关闭连接
  • commit()提交
  • cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor对象

  • 用于执行sql语句,使用频度最高的语句为select、insert、update、delete
  • 获取Cursor对象:调用Connection对象的cursor()方法
cs1=conn.cursor()

对象的方法:

  • close()关闭
  • execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行insert、update、delete语句,也可以执行create、alter、drop等语句
  • fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
  • fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回

对象的属性:

  • rowcount只读属性,表示最近一次execute()执行后受影响的行数
  • connection获得当前连接对象

增删改查

增删改

from pymysql import *


def main():
    
        # 链接mysql数据库,返回连接
        conn = connect(host="localhost", port=3306, database="test", user="root", password="123456", charset="utf8")
    
        # 获取游标
        cur = conn.cursor()

        # 执行insert语句,并返回受影响的函数
        count = cur.execute("insert into goods_cates(name) values('笔记本')")
        print(count)
    
        count = cur.execute("insert into goods_cates(name) values('硬盘')")
        print(count)
    
        # 更新
        count = cur.execute("update goods_cates set name='机械硬盘' where name='硬盘'")
        # 删除
        count = cur.execute("delete from goods_cates where name='机械硬盘' ")

        # 提交
        conn.commit()

        # 关闭链接
        conn.close()

if __name__ == "__main__":
        main()

查询

from pymysql import *


def main():
    
	# 链接mysql数据库,返回连接
	conn = connect(host="localhost", port=3306, database="test", user="root", password="123456", charset="utf8")
    
	# 获取游标
	cur = conn.cursor()
	
	# 查询
	count = cur.execute("select * from goods_cates")
	print("查询到了%d条数据" % count)

	# 获取一行数据
	print(cur.fetchone())

	# 获取多行数据
	print(cur.fetchmany(3))

	# 获取所有的数据
	print(cur.fetchall())	

	# 关闭链接
	conn.close()

if __name__ == "__main__":
        main()

附录

python中安装pymysql

在shell中执行如下命令:

$ sudo pip3 install pymysql

验证是否成功安装pymysql,在ipython3中执行:

import pymysql
原文地址:https://www.cnblogs.com/zhangfengxian/p/10204198.html