欢迎访问宙启技术站
智能推送

数据库操作:使用Python函数,对数据库进行增删改查等操作,例如MySQL、MongoDB等。

发布时间:2023-06-03 05:42:16

数据库操作是应用到现代信息技术中的又一复杂有价值的工作,有着重要的作用。在数据采集、存储、处理、分析、挖掘等方面,数据库操作是不可或缺的。在众多的数据库中,MySQL和MongoDB都是最常用的两个数据库。本文将会通过Python编写相应的函数,并讲解它们的基本用法。

一、MySQL数据库管理操作

1、安装MySQL 

Python自带了MySQL模块,因此在使用Python与MySQL交互时,我们要先安装MySQL。

安装命令:(注:以下操作基于Mac OS)

brew install mysql

2、连接MySQL 

连接到MySQL的基本方式是使用MySQLdb。Python的MySQLdb模块是我们非常常用的一个模块,可以直接在Python中使用SQL进行数据操作,包括创建数据库和表等。

除此之外,我们还要使用其他库配置MySQL参数。例如,{host}为MySQL数据库地址,{port}为MySQL服务的端口(默认为3306),{user}为MySQL用户名,{password}为MySQL密码,{database}为MySQL的数据库名。

pip install mysqlclient

import MySQLdb

import pymysql.cursors

#打开连接,连接MySQL数据库,传入参数为:host,user,password,database

def open_connect(**config):

    conn = pymysql.connect(host=config['host'],

                             user=config['user'],

                             password=config['password'],

                             database=config['database'],

                             port=config['port'])

    return conn

#关闭连接

def close_connect(conn):

    conn.close()

3、创建表 

创建MySQL数据表基本的SQL语句如下:

create table 表名 (

    字段1 数据类型,

    字段2 数据类型,

    ……

);

Python代码实现:

def create_table(conn,table_name,**columns):

    with conn.cursor() as cursor:

        columns_str = ""

        for i,column in enumerate(columns):

            if i == len(columns) - 1:

                columns_str += "" + column + "" + " " + columns[column]

            else:

                columns_str += "" + column + "" + " " + columns[column] + ","

        sql = "create table if not exists {} ({})".format(table_name,columns_str)

        cursor.execute(sql)

        conn.commit()

4、数据插入 

向MySQL数据表中插入一条记录的SQL语句如下:

insert into 表名 (字段1, 字段2, ……, 字段N) 

values (值1, 值2, ……, 值N);

Python编写实现:

#插入一条数据SQL

def insert_data(conn,table_name,**columns_values):

    with conn.cursor() as cursor:

        columns_str = ""

        values_str = ""

        for i,column in enumerate(columns_values):

            if i == len(columns_values) - 1:

                columns_str += "" + column + ""

                values_str += str(columns_values[column])

            else:

                columns_str += "" + column + ","

                values_str += str(columns_values[column]) + ","

        sql = "insert into {} ({}) values ({})".format(table_name,columns_str,values_str)

        cursor.execute(sql)

        conn.commit()

5、数据修改 

修改MySQL数据表中的记录的SQL语句如下:

update 表名 

set 字段1=新值, 字段2=新值, ……, 字段N=新值  

where 条件;

Python代码实现:

#更新数据SQL

def update_data(conn,table_name,condition_dict,**update_dict):

    with conn.cursor() as cursor:

        update_str = ""

        for i,update_column in enumerate(update_dict):

            if i == len(update_dict) - 1:

                update_str += "" + update_column + "" + "=" + str(update_dict[update_column])

            else:

                update_str += "" + update_column + "" + "=" + str(update_dict[update_column]) + ","

        condition_str = ""

        for i,condition in enumerate(condition_dict):

            if i == len(condition_dict) - 1:

                condition_str += "" + condition + "" + "=" + str(condition_dict[condition])

            else:

                condition_str += "" + condition + "" + "=" + str(condition_dict[condition])

        sql = "update {} set {} where {}".format(table_name,update_str,condition_str)

        cursor.execute(sql)

        conn.commit()

6、数据查询 

查询MySQL数据表中的记录的SQL语句如下:

select 字段1, 字段2, ……, 字段N 

from 表名 

where 条件语句 

order by 字段1, 字段2, ……, 字段N [asc|desc];

Python代码实现:

#查询数据SQL

def select_data(conn,table_name,**condition_dict):

    with conn.cursor() as cursor:

        condition_str = ""

        for i,condition in enumerate(condition_dict):

            if i == 0:

                condition_str += "" + condition + "" + "=" + str(condition_dict[condition])

            else:

                condition_str += " and " + "" + condition + "" + "=" + str(condition_dict[condition])

        if len(condition_dict) > 0:

            sql = "select * from {} where {}".format(table_name,condition_str)

        else:

            sql = "select * from {}".format(table_name)

        cursor.execute(sql)

        result = cursor.fetchall()

        return result

二、MongoDB数据库管理操作

1、安装MongoDB 

在使用Python交互MongoDB之前,我们先要安装mongoDB,具体安装方式可参考官方文档:

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

安装完成后,我们若要获取Python连接到mongoDB的IP地址与端口号,则可在mongoDB安装目录下的bin中使用mongo命令连接mongoDB,并使用show dbs命令查看,如下图所示:

2、连接MongoDB 

连接到MongoDB基本的方式是使用pymongo。Python的pymongo模块是我们非常常用的一个模块,可以直接在Python中使用MongoDB进行数据操作。

pip install pymongo

#打开连接,连接MongoDB服务器,传入参数为:host,port

def open_connect(**config):

    myclient = pymongo.MongoClient("mongodb://{}:{}".format(config['host'],config['port']))

    return myclient

#关闭连接

def close_connect(conn):

    conn.close()

3、插入数据 

向mongoDB中插入一条数据使用的MongoDB Shell方式是:

db.表名.insertOne({字段1:值1, 字段2:值2, ……, 字段N:值N});

Python组装代码实现:

def insert_one_data(conn,db_name,col_name,**doc):

    db = conn[db_name]

    collection = db[col_name]

    collection.insert_one(doc)

4、修改数据 

在mongoDB中修改一条数据使用的MongoDB Shell方式是:

db.表名.updateOne({条件语句},{$set:{字段1:新值, 字段2:新值, ……, 字段N:新值}});

Python组装代码实现:

def update_one_data(conn,db_name,col_name,condition_dict,**update_dict):

    db = conn[db_name]

    collection = db[col_name]

    collection.update_one(condition_dict,{'$set':update_dict})

5、删除数据 

在mongoDB中删除一条数据使用的MongoDB Shell方式是:

db.表名.deleteOne({条件语句});

Python组装代码实现:

def delete_one_data(conn,db_name,col_name,**condition_dict):

    db = conn[db_name]

    collection = db[col_name]

    collection.delete_one(condition_dict)

6、查询数据 

在mongoDB中查询所有数据使用的MongoDB Shell方式是:

db.表名.find();

Python组装代码实现:

def select_all_data(conn,db_name,col_name):

    db = conn[db_name]

    collection = db[col_name]

    result = collection.find()

    return result

示例代码:

#!/usr/bin/python3

# -*-coding:utf-8 -*-

import pymongo

import pymysql.cursors

#连接MySQL

def open_connect(**config):

    conn = pymysql.connect(host=config['host'],

                             user=config['user'],

                             password=config['password'],

                             database=config['database'],

                             port=config['port'])

    return conn

#关闭连接

def close_connect(conn):

    conn.close()

#创建MySQL表

def create_table(conn,table_name,**columns):

    with conn.cursor() as cursor:

        columns_str = ""

        for i,column in enumerate(columns):

            if i == len(columns) - 1:

                columns_str += "" + column + "" + " " + columns[column]

            else: