pymysql的安装与使用——python+pymysql

一、pymysql的安装

1、下载pymysql 库(第三方机构)

  • 方法一:dos下安装:

  • 方法二:在pycharm中下载

2、使用pymysql

(1)数据安装好,能连接

(2)连接数据库

3、连接方式

(1)连接方式:pymysql.Connection 或者pymysql.connect 

(2)包含内容

  • a.host 主机:填写IP地址
  • b.user  数据库用户名
  • c.password 或passwd  密码:
  • d.databases  或db  库名
  • e.port  端口  :默认3306
  • f.charset ='utf8'    编码格式
  • 案例

(a)db=pymysql.Connection(host="192.168.157.128",user="root",password="123456",database="test",port=3306,charset='utf8')

(3)将连接内容设置成一个变量,然后创建一个游标对象

db.cursor

(4)使用游标对象去执行sql语句

(5)在根据需要显示内容使用 fetchone,fetchall,fetchmany

# import pymysql  #导入pymysql
# lj=pymysql.connect(
#     host="192.168.1.210",user="root",passwd="123456",port=3306,database="hh",charset="utf8"
# )
# yb=lj.cursor()   #创建游标
# sql="select * from student"  #sql语句
# yb.execute(sql)    #执行语句
# one=yb.fetchone() #查看执行一行数据
# print(one)
# many=yb.fetchmany(size=3)
# print(many)
# all=yb.fetchall()
# print(all)

二、pymysql操作数据库的增删改查

1、删除

# import pymysql  #导入pymysql
# lj=pymysql.connect(
#     host="192.168.1.210",user="root",passwd="123456",port=3306,database="hh",charset="utf8"
# )
# yb=lj.cursor()   #创建游标

# sql="delete from student where id=40"
# yb.execute(sql)

2、插入数据

# import pymysql  #导入pymysql
# lj=pymysql.connect(
#     host="192.168.1.210",user="root",passwd="123456",port=3306,database="hh",charset="utf8"
# )
# yb=lj.cursor()   #创建游标
# sql1="insert into student(id) values(1)"
# yb.execute(sql1)

3、修改数据

# import pymysql  #导入pymysql
# lj=pymysql.connect(
#     host="192.168.1.210",user="root",passwd="123456",port=3306,database="hh",charset="utf8"
# )
# yb=lj.cursor()   #创建游标
# sql2="update student set id=40 where id=1"
# yb.execute(sql2)

三、数据库封装

import pymysql
class Sjk(object):
    def __init__(self,host,user,passwd,port,database,):
        self.host=host
        self.user=user
        self.passwd=passwd
        self.port=port
        self.database=database
    def lj(self):
        lj=pymysql.connect(
            host=self.host,user=self.user,passwd=self.passwd,port=self.port,
            database=self.database,charset="utf8"
        )
        return lj
    def one(self,sql1):
        yb=self.lj().cursor()
        yb.execute(sql1)
        print(yb.fetchone())
    def many(self,sql2,x):
        yb=self.lj().cursor()
        yb.execute(sql2)
        print(yb.fetchmany(size=x))
    def all(self,sql3):
        yb=self.lj().cursor()
        yb.execute(sql3)
        print(yb.fetchall())
if __name__ == '__main__':
    dx=Sjk(
        host="192.168.1.210", user="root", passwd="123456", port=3306, database="hh"
    )
    dx.one("select * from student")
    dx.many("select * from student",3)
    dx.all("select * from student")

*在测试,你可以通过数据库造数据,删除数据,修改数据,

断言

1.查询后台数据

2.造数据

3.删除数据,让数据不冗余

posted @ 2025-03-27 11:39  uai  阅读(393)  评论(0)    收藏  举报