python和Mysql的交互

python和Mysql的交互

  1. 在Linux系统安装pymysql模块:sudo pip install pymysql
    在window10系统安装pymysql模块:pip install pymysql

python中操作Mysql步骤:

  1. 开始
    • 创建connection
    • 获取cursor
    • 执行查询、执行命令、获取数据、处理数据
    • 关闭coursor
    • 关闭connertion>结束
import pymysql
# 连接数据库
connt = pymysql.connect(host="localhost", port=3306, user="root", password="gwl2003.520", database="gwllove", charset="utf8")
curt = connt.cursor()
curt.execute("select * from db_yhm_city")
# 想要几行就显示几行
# data = curt.fetchmany(100)
# 显示一行
# data = curt.fetchone()
# 显示全部
data = curt.fetchall()
for i in data:
    print(i)
print(data)
curt.close()
connt.close()

引入模块:

from pymysql import *

Connection对象:

  • 用于建立与数据库的连接
  • 创建对象:调用connect方法
  • conn = connect(参数列表)
  • 参数host :连接数据库的主机
  • 参数prot:;连接数据库的主机端口默认是3306
  • 参数database: 数据库的名称
  • 参数charset:通信采用的编码格式, 推荐使用utf8

对象的方法:

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

Cursor对象:

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

  • 获取Cursor对象:调用connection()方法

  • cs1 = cursor()
    对象方法:

  • close()关闭

  • execute(operation[, paramenrers])执行语句, 返回受影响的行数, 主要用于执行insert update delete语句 也可以执行 create alter drop等语句

  • fetchone()执行查询语句时 获取查询结果集的第一个行数据 返回一个元组

  • fetchall()执行查询 获取结果集的所有行 一行构成一个元组 在将这些元组装入一个元组返回

对象的属性

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

python 插入数据

一定要使用commit方法才能提交数据

import pymysql
connt = pymysql.connect(host="localhost",port=3306, user="root", password="gwl2003.520", database="gwllove", charset="utf8")
curt = connt.cursor()
# curt.execute("select * from gwl3")
#插入数据
# curt.execute("show create table gwl3")
curt.execute("insert into gwl3 (name) values('gwl-3')")
connt.commit()
print("数据插入成功")
curt.close()
connt.commit()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值