pymysql操作笔记

下载pyMySQL库 pip install或pycharm编辑器里下载
import pymysql #导入pymysql
db=pymysql.connect( #连接数据库
host="192.168.126.129", #主机地址
user="root", #用户名
passwd="123456", #密码
db="db3", #数据库名
port=3306, #端口
charset="utf8" #编码格式
)
yb=db.cursor() #创建游标对象
sql1="select * from student1;" #输入sql语句
yb.execute(sql1) #执行sql语句
print(yb.fetchall())

使用类管理pyMySQL
import pymysql

class sql(object):
def init(self):
pass

def connect(self):
db = pymysql.connect(
host="192.168.126.129",
user="root",
password="123456",
database="db3",
port=3306,
charset="utf8"
)
self.yb=db.cursor()

def fetchone(self,db):
self.yb.execute(db)
result = self.yb.fetchone()
print(result)

def fetchall(self,db):
self.yb.execute(db)
result = self.yb.fetchall()
print(result)

def fetchmany(self,db,size):
self.yb.execute(db)
result = self.yb.fetchmany(size=size)
print(result)

if name == 'main':
yj="select * from student1"
sql=sql()
sql.connect()
sql.fetchone(yj)
sql.fetchall(yj)
sql.fetchmany(yj,3)

posted on 2026-05-29 10:44  一般路过uuz  阅读(6)  评论(0)    收藏  举报