mysql的python操作,利用python进行mysql数据库的管理

在进行操作之前假设已经在库里建好表了,如果没有的话就执行下面的吧:

create database xue_xiao character set utf8 collate utf8_general_ci;

use xue_xiao;

create table xue_sheng(id int, xing_ming varchar(50), fen_shu int, xing_bie char(2));

insert into xue_sheng values(1,'张三',90,'男');

insert into xue_sheng values(2,'李四',70,'男');

insert into xue_sheng values(3,'李小红',80,'女');

mysql的python操作,利用python进行mysql数据库的管理_第1张图片

安装pymysql

pip install pymysql

利用python连接xue_sheng库

'localhost': mysql机器的ip
'root':MySQL用户
'1234':数据库的密码
'xue_xiao':需要连接数据库
sql:是要执行的指令
cursor.execute(sql):执行指令
returns :指令影响了多少行
cursor.fetchone():一次获取一行放回结果,类似readline
cursor.fetchall():返回所有结果,类似readlines

db= pymysql.connect('localhost','root','1234','xue_xiao')
cursor = db.cursor()
sql = ''select * from xue_sheng'' 
returns = cursor.execute(sql)#对
dataone = cursor.fetchone()
dataall = cursor.fetchall()
print(dataall)
print(dataone)
cursor.close()
db.close()

结果


写一个关于mysql的驱动

import pymysql


class MySQL():
    def __init__(self, host, user, passwd, dbName):
        self.host =host
        self.user = user
        self.passwd = passwd
        self.dbName = dbName
    
    def connect(self):
        self.db = pymysql.connect(self.host, self.user, self.passwd, self.dbName)

        self.cursor = self.db.cursor()
        
    def close(self):
        self.cursor.close()
        self.db.close()
    
    def get_one(self, sql):
        res = None
        try:
            self.connect()
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
            self.close()
        except:
            print('查询失败')
        return res
    
    def get_all(self, sql):
        res = None
        try:
            self.connect()
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
            self.close()
        except:
            print('查询失败')
        return res
    
        def insert(self,sql):
            return self.__edit(sql)
            
        def update(self,sql):
            return self.__edit(sql)
            
        def delete(self,sql):
            return self.__edit(sql)
            
        def __edit(self,sql):
            count = 0
            try:
                self.connet()
                count = self.cursor.execute(sql)
                self.db.commit()
                self.close()
            except:
                print('事物提交失败')
                self.db.roolback()
            return count 
db= MySQL('localhost','root','1234','xue_xiao')
dataall = db.get_all('select * from xue_sheng')
dataone = db.get_one('select * from xue_sheng' )
print(dataall)
print(dataone)

结果图


你可能感兴趣的:(mysql的python操作,利用python进行mysql数据库的管理)