先打开数据库,
将数据库打开
二、下载 pip install pymysql 或者pycharm下载
三、导入pymysql
import pymysql
创建一个连接对象
Connect=connect=Connection=connection.Connection
连接的参数:
import pymysql #下载MySQL模块导入
lj=pymysql.connect(
host="192.168.3.128",db="test",user="root",password="123456",
port=3306,charset="utf8"
)
yb=lj.cursor() # 创建一个游标
sql="select * from student" #sql语句
yb.execute(sql) #通过游标执行sql语句
one=yb.fetchone() #获取第一行数据
print(one)
many=yb.fetchmany(3)
print(many)
all=yb.fetchall()
print(all)
四、通过pymysql对数据进行增删改查
1、查
import pymysql
lj=pymysql.connect(
host="192.168.3.128",db="test",user="root",password="123456",
port=3306,charset="utf8")
yb=lj.cursor() # 创建一个游标
sql="select * from student" #sql语句
yb.execute(sql) #通过游标执行sql语句
one=yb.fetchone() #获取第一行数据
print(one)
2、插入数据
import pymysql
lj=pymysql.connect(
host="192.168.3.128",db="test",user="root",password="123456",
port=3306,charset="utf8"
)
yb=lj.cursor() # 创建一个游标
sql="INSERT into student(age) VALUES(24)" #sql语句
yb.execute(sql) #通过游标执行sql语句
3、删除delete
import pymysql
lj=pymysql.connect(
host="192.168.3.128",db="test",user="root",password="123456",
port=3306,charset="utf8"
)
yb=lj.cursor() # 创建一个游标
sql="DELETE from student where age=24" #sql语句
yb.execute(sql) #通过游标执行sql语句
四、update修改数据
import pymysql
lj=pymysql.connect(
host="192.168.3.128",db="test",user="root",password="123456",
port=3306,charset="utf8"
)
yb=lj.cursor() # 创建一个游标
sql="UPDATE student set age=100 where age=24" #sql语句
yb.execute(sql) #通过游标执行sql语句
五、将查询三种的方法封装
import pymysql
class Sjk(object):
def __init__(self,host,user,passwd,port,db): #自定义函数
self.host=host
self.user=user
self.passwd=passwd
self.port=port
self.db=db
def lj(self):
lj1=pymysql.connect(
host=self.host,db=self.db,user=self.user,password=self.passwd,
port=self.port,charset="utf8"
)
return lj1
def one(self,sql):
l=self.lj()
yb=l.cursor()
yb.execute(sql)
one=yb.fetchone()
print(one)
def many(self,sql,size):
l=self.lj()
yb=l.cursor()
yb.execute(sql)
many=yb.fetchmany(size=size)
print(many)
def all(self,sql):
l = self.lj()
yb = l.cursor()
yb.execute(sql)
all=yb.fetchall()
print(all)
if __name__ == '__main__':
dx=Sjk(
host="192.168.3.128", db="test", user="root", passwd="123456",
port=3306,
)
dx.one("select * from student")
dx.many("select * from student",3)
dx.all("select * from student")