MySQL与python交互

这里介绍两种连接方法,一种是使用安装的第三方库pymysql【针对python3】进行连接,另外一种是采用pandas里的模块进行连接,个人推荐后者。

 

一、使用pymsql 库进行连接

这里使用的【数据库名:test_my    表名:department   字段名为:Id 和 Name】

1. 简单连接的小例子

    (1). 查找记录。

from pymysql import *

try:

    # 连接包括六部分组成:主机、端口、数据库名、用户名、密码、编码
    
    ## 主机:本地使用"localhost"或127.0.0.1【其他使用ip地址即可】、 端口默认3306、 "test_my" 是数据库名
    ## 用户名默认root、密码为空【若有密码填入密码】、编码'utf8'
    
    conn = connect(host='localhost',port=3306,database='test_my',user='root',passwd='',charset='utf8')  # 1.创建连接
    cur = conn.cursor()                         # 2.创建游标
    
    id = input('请输入要查找的Id:')   
    sql = 'select * from department where Id=%s' # 3.编写SQL语句    %s 为占位符
    cur.execute(sql,[id])  # 4. 游标执行sql语句【传入参数】
    print(cur.fetchall())    # 5. 游标查找全部 【把fetchall 改为fetchone为查找一条数据】

    cur.close()    ## 6. 关闭游标
    conn.close()   ## 7. 关闭连接

except Exception:
    print("错误")

查找前的数据库内容:

MySQL与python交互_第1张图片

程序运行结果

(2)增、删、改数据库(cud)

    这里与上述查询有些差异、增删改数据库需要使用事物、需要对执行后的语句,再进行提交,即commit()操作。而查询使用的是游标再feachone()或feachall()。增删改则为在游标执行完sql语句后,再进行连接.commit()操作。例子如下

from pymysql import *

try:

    # 连接包括六部分组成:主机、端口、数据库名、用户名、密码、编码
    
    ## 主机:本地使用"localhost"或127.0.0.1【其他使用ip地址即可】、 端口默认3306、 "test_my" 是数据库名
    ## 用户名默认root、密码为空【若有密码填入密码】、编码'utf8'
    
    conn = connect(host='localhost',port=3306,database='test_my',user='root',passwd='',charset='utf8')  # 1.创建连接
    cur = conn.cursor()                         # 2.创建游标

    ############  不同于上述 查询的 部分
    name = input('请输入要插入的姓名:')
    sql_s = 'insert into department(Name) values(%s)' # 3.编写sql 插入语句 Name是字段
    cur.execute(sql_s,[name])  # 4. 游标执行sql语句【传入参数】
    conn.commit()              # 5. 连接提交事务
    ###########

    cur.close()    ## 6. 关闭游标
    conn.close()   ## 7. 关闭连接
    print('ok')

except Exception:
    print("错误")

2. 编写脚本【便于重复使用】

(1)mysql_help.py 【已经编写好的模块、用于增删改查】,具体代码如下

from pymysql import *

class MysqlHelper(object):
    def __init__(self,host,port,database,user,passwd,charset='utf8'):
        self.host = host
        self.port = port
        self.database = database
        self.user = user
        self.passwd = passwd
        self.charset = charset

    def open(self):
        """创建"""
        self.conn = connect(host=self.host,port=self.port,\
                            database=self.database,passwd=self.passwd,charset=self.charset)
        self.cur = self.conn.cursor()


    def close(self):
        """关闭"""
        self.cur.close()
        self.conn.close()


    def cud(self,sql,params):
        """增删改"""
        self.open()
        self.cur.execute(sql,params)
        self.conn.commit()
        self.close()
        print('修改成功')

    def r_s(self,sql,params):
        """查找"""
        try:
            self.open()
            self.cur.execute(sql,params)
            s_result = self.cur.fetchone()
            self.close()
            return s_result
        
        except Exception:
            print("错误")

(2)调用上述脚本,从而更加便捷的进行增删改查【更多精力放在SQL语句编写上】

   再编写一个python文件叫sql_execute.py,让这个文件与上述的基本脚本文件mysql_help.py 放在同一目录下。

 

执行前的数据库内容如图:

MySQL与python交互_第2张图片

  1)当需要执行查询操作时,sql_execute.py文件调用的程序如下所示:

import mysql_help

##  1.查找
id_no = input('请输入要查询的Id号:')

sql_s = 'select * from department where Id = %s'

mysqlhelper = mysql_help.MysqlHelper('localhost',3306,'test_my','root','')

result = mysqlhelper.r_s(sql_s,[id_no])

print(result)

结果如下所示:

        2) 当执行修改操作【这里仅举例了更新操作、其余类似】时,程序如下所示:

import mysql_help

####  2. 更新操作

id_no = input('请输入要变更的Id号:')
name = input('请输入要变更后的姓名:')

sql_u = 'update department set Name = %s where Id = %s'

mysqlhelper = mysql_help.MysqlHelper('localhost',3306,'test_my','root','')
mysqlhelper.cud(sql_u,[name,id_no])

程序执行结果

执行前的数据库内容为:

MySQL与python交互_第3张图片  执行上述程序后结果为MySQL与python交互_第4张图片.

所以以后直接可以使用脚本mysql_help.py  作为自己的基础脚本。直接调用即可,把精力放在SQL语句上。

 

二、使用pandas库进行数据库连接查询

使用pandas.read_sql()

注:这里只针对查询操作【需要安装的第三方库、mysql.connector、pandas、sqlalchemy】

查询使用如下:

import pandas as pd
from sqlalchemy import create_engine

def readsql(sql_lag,db='test_my'):
    engine = create_engine('mysql+mysqlconnector://root:""@localhost:3306/{0}?charset-utf8'.format(db))
    df = pd.read_sql(sql_lag,engine)
    return df

sql_s = """
select * from department
    """

df1 = readsql(sql_s)

print(type(df1))
print(df1)

其中输出结果为DataFrame格式。即数据框格式。便于数据处理分析。

输出结果如下图所示:

MySQL与python交互_第5张图片

 

 

 

 

你可能感兴趣的:(数据分析)