PyMySQL

10 篇文章 0 订阅

安装模块:

pip install PyMySQL

主要有两个对象,Collection对象和Cursor对象。

Collection对象

  • 用于建立与数据库的连接
  • 创建对象,调用connect()方法
  • 参数host,连接的mysql主机,如果是本机则是‘localhost’
  • 参数port,连接的 MySQL主机端口,默认是3306
  • 参数db,数据库的名称
  • 参数user,连接的用户名
  • 参数password,连接的密码
  • 参数charset,通信采用的编码方式,默认是‘gb2312’,要求与数据库创建时指定的编码一致,否则会出现中文乱码

对象的方法

  • close()关闭连接
  • commit())事务,所有需求要提交才能生效
  • rollback()事务,放弃之前的操作
  • cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor

  • 执行sql语句
  • 创建对象:调用Connection对象的cursor方法

对象的方法

  • close()关闭
  • execute(operation[,parameters])执行语句,返回受影响的行数
  • fetchone()执行查询语句时,获取查询结果的第一个行数据,返回一个元组
  • next()执行查询语句时时,获取当前执行的下一行
  • fetchall()执行查询语句时,获取结果的所有行,一行构成一个元组,再将这些元组装入一个元组返回
  • scroll(value[,mode])将行指针移动到这个位
  1. mode表示移动的方式
  2. mode的值默认是relative,表示基于当前行移动到value,value为正则向下移动,反之向上移动
#coding:utf-8
import pymysql
import  datetime

connection = None
cursor = None

try:
    #创建数据库连接,一个连接只能连接一个数据库

    connection = pymysql.connect('localhost', 'root', 'CENTos_', 'test')

    #创建cursor

    cursor = connection.cursor()

    sql = 'select * from t_user'

    #cursor执行sql
    try:
        cursor.execute(sql)

        #获取cursor执行sql之后的第一行结果

        t_user = cursor.fetchall()
        print(t_user)
    except Exception as ex:
        print(ex)

except Exception as ex:
    print(ex)
finally:
    if connection:
        cursor.close()
    if cursor:
        connection.close()

 insert语句

#coding:utf-8
import pymysql
import  datetime

connection = None
cursor = None

try:
    #创建数据库连接,一个连接只能连接一个数据库,connection自动加入事务

    connection = pymysql.connect('localhost', 'root', 'CENTos_', 'test')

    #创建cursor

    cursor = connection.cursor()

    sql = "insert into t_user values (%s, %s)"
    #有安全隐患
    #sql = "insert into t_user values ('%s','%s')"%('7', 'g')
    print(sql)
    #cursor执行sql
    try:
        cursor.execute(sql, (8, 'h'))
        connection.commit()
        #获取cursor执行sql之后的第一行结果

        t_user = cursor.fetchall()
        print(t_user)
    except Exception as ex:
        connection.rollback()
        print(ex)

except Exception as ex:
    print(ex)
finally:
    if connection:
        cursor.close()
    if cursor:
        connection.close()

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值