Python----操作MySql数据库2

走远了吗. 提交于 2020-02-26 21:13:34

Python学习之路,点击有全套Python笔记

环境配置及依赖安装
# 安装命令
pip install mysqlclient

失败的话就用这个网址,搜索Mysqlclient,挑一个对应的版本下载至一个地方,然后在下载的哪里,执行 pip install 刚刚下载的文件名.whl
https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
在这里插入图片描述
验证,improt MySQLdb
在这里插入图片描述

使用python链接数据库
import MySQLdb
# 获取链接
try:
    conn = MySQLdb.connect(
        host='localhost',
        user='root',
        passwd='root',
        db='school',
        port=3306,
        charset='utf8'
    )
    # 获取数据
    cursor1 = conn.cursor()
    cursor1.execute("SELECT * FROM `students` WHERE `sex`='女';") 	
    rest = cursor1.fetchone()
    print(rest)  # (1, '张三', '没有昵称', '女', datetime.datetime(2020, 2, 26, 15, 46, 14))

    # 关闭链接
    conn.close()
except MySQLdb.error as e:
    print('ERROR: %s' %e)
使用python进行查询
import MySQLdb

class MysqlSearch(object):

    def __init__(self):
        self.get_conn()

    def get_conn(self):
    # 获取链接
        try:
            self.conn = MySQLdb.connect(
                host='localhost',
                user='root',
                passwd='root',
                db='school',
                port=3306,
                charset='utf8'
            )
        except MySQLdb.Error as e:
            print('ERROR: %s' % e)

    def close_conn(self):
        try:
            if self.conn:
                # 关闭链接
                self.conn.close()
        except MySQLdb.Error as e:
            print('ERROR: %s' % e)

    def get_one(self):
        # 准备SQL
        sql = "SELECT * FROM `students` WHERE `sex`='女';"
        # 找到cursor
        cursor1 = self.conn.cursor()
        # 执行sql
        cursor1.execute(sql)
        # print(cursor1.rowcount)  # 查行
        # print(cursor1.description)  # 查域的名字
        # 拿到结果
        rest = dict(zip([k[0] for k in cursor1.description], cursor1.fetchone()))
        # 处理数据
        # 关闭cursor/链接
        cursor1.close()
        self.close_conn()
        return rest

    def get_all(self, page, page_size):
        # 准备SQL
        sql = "SELECT * FROM `students` WHERE `sex`='女';"
        # 找到cursor
        cursor1 = self.conn.cursor()
        # 执行sql
        cursor1.execute(sql)
        # print(cursor1.rowcount)  # 查行
        # print(cursor1.description)  # 查域的名字
        # 拿到结果
        rest = [dict(zip([k[0] for k in cursor1.description], row))
        for row in cursor1.fetchall()]
        # 处理数据
        # 关闭cursor/链接
        cursor1.close()
        self.close_conn()
        return rest

def main():
    obj = MysqlSearch()
    # rest = obj.get_one()
    # print(rest['name'])
    rest_all = obj.get_all()
    for item in rest_all:
        print(item)
        print('------------')

if __name__ == '__main__':
    main()
使用python进行增加/删除
import MySQLdb

class MysqlSearch(object):

    def __init__(self):
        self.get_conn()

    def get_conn(self):
    # 获取链接
        try:
            self.conn = MySQLdb.connect(
                host='localhost',
                user='root',
                passwd='root',
                db='school',
                port=3306,
                charset='utf8'
            )
        except MySQLdb.Error as e:
            print('ERROR: %s' % e)

    def close_conn(self):
        try:
            if self.conn:
                # 关闭链接
                self.conn.close()
        except MySQLdb.Error as e:
            print('ERROR: %s' % e)

    def get_one(self):
        # 准备SQL
        sql = "SELECT * FROM `students` WHERE `sex`='女';"
        # 找到cursor
        cursor1 = self.conn.cursor()
        # 执行sql
        cursor1.execute(sql)
        # print(cursor1.rowcount)  # 查行
        # print(cursor1.description)  # 查域的名字
        # 拿到结果
        rest = dict(zip([k[0] for k in cursor1.description], cursor1.fetchone()))
        # 处理数据
        # 关闭cursor/链接
        cursor1.close()
        self.close_conn()
        return rest

    def get_all(self, page, page_size):
        # 准备SQL
        sql = "SELECT * FROM `students` WHERE `sex`='女';"
        # 找到cursor
        cursor1 = self.conn.cursor()
        # 执行sql
        cursor1.execute(sql)
        # print(cursor1.rowcount)  # 查行
        # print(cursor1.description)  # 查域的名字
        # 拿到结果
        rest = [dict(zip([k[0] for k in cursor1.description], row))
        for row in cursor1.fetchall()]
        # 处理数据
        # 关闭cursor/链接
        cursor1.close()
        self.close_conn()
        return rest

    def add_one(self):
        try:
            # 准备sql
            sql = "INSERT INTO `students` (`id` `name`, `nickname`, `sex`, `in_time`) VALUES(%s, %s, %s, %s );"
            # 获取链接和cursor
            cursor1 = self.conn.cursor()
            # 执行sql
            # 提交数据到数据库
            cursor1.execute(sql, ('1', '张一', '三哥', '男', 'NOW()'))
            cursor1.execute(sql, ('张九', '三哥', '男', 'NOW()'))
            # 提交事务
            self.conn.commit()
            # 关闭cursor和链接
            cursor1.close()
            self.close_conn()
        except :
            print('error')

def main():
    obj = MysqlSearch()
    # rest = obj.get_one()
    # print(rest['name'])
    # rest_all = obj.get_all()
    # for item in rest_all:
    #     print(item)
    #     print('------------')
    obj.add_one()

if __name__ == '__main__':
    main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!